13

I am just wondering what the best way of extracting "parameters" from an URL would be, using PHP.

If I got the URL:

http://example.com/user/100

How can I get the user id (100) using PHP?

jww
  • 97,681
  • 90
  • 411
  • 885
Jonathan Clark
  • 19,726
  • 29
  • 111
  • 175

4 Answers4

19

To be thorough, you'll want to start with parse_url().

$parts=parse_url("http://example.com/user/100");

That will give you an array with a handful of keys. The one you are looking for is path.

Split the path on / and take the last one.

$path_parts=explode('/', $parts['path']);

Your ID is now in $path_parts[count($path_parts)-1].

jww
  • 97,681
  • 90
  • 411
  • 885
Brad
  • 159,648
  • 54
  • 349
  • 530
9

You can use parse_url(), i.e.:

$parts = parse_url("http://x.com/user/100");
$path_parts= explode('/', $parts[path]);
$user = $path_parts[2];
echo $user; 
# 100

parse_url()

This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.

This function is notmeant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
3
$url = "http://example.com/user/100";
$parts = Explode('/', $url);
$id = $parts[count($parts) - 1];
jww
  • 97,681
  • 90
  • 411
  • 885
abarrington
  • 166
  • 9
2

I know this is an old thread but I think the following is a better answer: basename(dirname(__FILE__))

Dustin
  • 123
  • 1
  • 10