Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request uri php: get first level

Tags:

php

If I had a url such as www.example.com/test/example/product.html

How would I be able to get just the test part(so the top level)

I understand you would use $_SERVER['REQUEST_URI'] and maybe substr or trim

But I am unsure of how to do this, thank you!

like image 388
1321941 Avatar asked May 18 '12 23:05

1321941


2 Answers

Split the string into an array with explode, and then take the part you need.

$whatINeed = explode('/', $_SERVER['REQUEST_URI']);
$whatINeed = $whatINeed[1];

If you use PHP 5.4, you can do $whatINeed = explode('/', $_SERVER['REQUEST_URI'])[1];

like image 67
Samy Dindane Avatar answered Oct 20 '22 03:10

Samy Dindane


<?php
$url = 'http://username:[email protected]/test/example/product.html?arg=value#anchor';

print_r(parse_url($url));

$urlArray = parse_url($url);

/* Output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /test/example/product.html
    [query] => arg=value
    [fragment] => anchor
)


*/

echo dirname($urlArray[path]);

/* Output:

/test    

*/
like image 38
Incognito Avatar answered Oct 20 '22 03:10

Incognito