georgevich georgevich - 2 months ago 17
PHP Question

Get second segment from url

How to get the second segment in URL without slashes ?
For example I have a URL`s like this

http://foobar/first/second


How to get the value where "first" stands ?

Answer

Use parse_url to get the path from the URL and then use explode to split it into its segments:

$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);

echo $uri_segments[0]; // for www.example.com/user/account you will get 'user'