Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parts of URL in PHP

Tags:

url

php

parsing

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?

like image 443
Jonathan Clark Avatar asked Aug 08 '11 16:08

Jonathan Clark


People also ask

How do I part a URL in PHP?

parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it. It parse an URL and return an associative array which contains its various components. parse_str() Function: The parse_str() function is used to parse a query string into variables.

HOW to fetch URL data in PHP?

The necessary superglobal variables such as $_SERVER['HTTPS'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PORT'] are used to get full URL in PHP. The variable HTTPS can easily retrieve the protocol in the URL of a webpage. If it returns a value “on”, then the protocol is HTTPS.

HOW to get URI segment in PHP?

Get URI Segments in PHP Use the following code to get URL segments of the current URL. It returns all the segments of the current URL as an array. $uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

HOW to get URL hash in PHP?

hash, //get the hash from url cleanhash = hash. replace("#", ""); //remove the # //alert(cleanhash); </script> <? php $hash = "<script>document.


1 Answers

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

like image 98
Brad Avatar answered Oct 04 '22 19:10

Brad