Question

This script should detect the last portion in the full path, and if it is stackoverflow output ok

$current_url = $_SERVER['REQUEST_URI'];

$current_url_arr = explode('/',$current_url);
$count = count($current_url_arr);

if($current_url_arr[$count-2] == 'stackoverflow'){
    echo 'ok';
}
else {
    echo 'not ok';
}

Example 1: www.myserver.ext/something/else/stackoverflow/ Output: ok


Example 2: www.myserver.ext/something/else/stackoverflow Output: not ok


Example 3: www.myserver.ext/something/else/stackoverflow/foo Output: not ok


I hope that you understand the idea. This script works fine, but I'm wondering if there is any better, elegant way to read last portion of URL?

Était-ce utile?

La solution

Yes! There's $_SERVER['PATH_INFO']:

if(isset($_SERVER['PATH_INFO'])) {
    $info = explode('/', trim($_SERVER['PATH_INFO'], '/'));

    if($info[count($info) - 1] === 'stackoverflow') {
        echo 'ok';
    } else {
        echo 'not ok';
    }
}

Autres conseils

if (preg_match("#stackoverflow/$#", $_SERVER['REQUEST_URI'])) {

    echo 'ok';
}

I think this would be the best way:

<?php

    $url = "www.myserver.ext/something/else/stackoverflow/";

    $fullpath = parse_url($url, PHP_URL_PATH);
    $paths = explode("/", $fullpath);
    $path = $paths[sizeof($paths)-1];

    if ($path === "stackoverflow") {
        # Condition satisfied
    }

?>

I think use of basename() is a better idea than explode(). basename() function will return last portion of url whether there is trailing slashes or not.

<?php
$uri = $_SERVER['REQUEST_URI'];
if(basename($uri) == 'stackoverflow') {
    echo 'ok';
} else {
    echo 'not ok';
}
?>

Hopefully this will help.

Please note, that if trailing characters in the input string will match the delimiter (boundary) string, explode() will produce en array with last item being an empty string. Thus your Example 3 will output ok.

www.myserver.ext/something/else/stackoverflow/foo/ will output not ok.

The shortest way to achieve your need is:

if (preg_match("#/stackoverflow/$#", $_SERVER['REQUEST_URI'])) {
    echo 'ok';
}

This will echo ok only if the url ends with /stackoverflow/.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top