Jonathan Clark
Jonathan Clark

Reputation: 20538

Get parts of URL in PHP

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?

Upvotes: 13

Views: 25250

Answers (4)

Pedro Lobito
Pedro Lobito

Reputation: 98861

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.

Upvotes: 9

Brad
Brad

Reputation: 163272

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].

Upvotes: 20

abarrington
abarrington

Reputation: 166

$url = "http://example.com/user/100";
$parts = Explode('/', $url);
$id = $parts[count($parts) - 1];

Upvotes: 3

Dustin
Dustin

Reputation: 123

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

Upvotes: 2

Related Questions