PHP: How to parse a URL
How to get the elements of a URL, and possibly associated parameters?
Two cases may arise: either the URL is in a string, and we want to find its parts, or it is a Web page and we want retrieve all the information about it or get data from a form.
To parse a URL in a string, two functions will be useful, parse_url and parse_str. The first splits a URL in parts just as the Location object in JavaScript, the second splits a string of parameters into variables and values.Comparison with JavaScript
The parse_url function is equivalent to the Location object in JavaScript. The keys of the associative array are replaced by the properties of the Location object.
The full URL is obtained with the constant __FILE__ which is predefined and does not belong to the table generated by parse_url.
| Data |
PHP
|
JavaScript
|
| Full URL |
__FILE__
|
location.href
|
| Protocol (http) |
scheme
|
protocol
|
| Domain |
host
|
hostname
|
| Directory and file |
path
|
pathname
|
| Anchor in the page |
fragment
|
hash
|
| Parameters |
query
|
search
|
| Port |
-
|
port
|
| Login |
user
|
-
|
| Password |
pass
|
-
|
Other differences:
- If one adds both an internal anchor and parameters, which is not correct, all will be involved to hash in JavaScript and to query PHP .
- In JavaScript the protocol includes the colon, as in http: but not in PHP.
Using the parse_url function
Example:
$url = "http://www.scriptol.com/how-to/parsing-url.php#content"; $arr = parse_url($url) print_r($arr);
This gives an associative array where the keys are detailed in the table above.
array( "scheme" => http, "host" => www.scriptol.com, "path" => /comment/parser-url.php, "fragment" => content )
Using the parse_str function
Example:
$parameters = $arr["query"]; parse_str($parameters, $data); print_r($data);
$data is an associative array, where key are variables given as parameters, and values, the content of these variables.
For example:
file.php?name=doe&number=50
This array will be generated:
array( "name" => doe, "number" => 50 )
Sources and download
- Source code of the online script.
- Source code of the local script.
- Archive containing sources and a demo page.
Part Two: Getting information on a Web page and data from a form.