1.11 Parsing a URL


You want to take a raw URL and make sense out of it.

Technique

Use the parse_url() and parse_str() functions to parse the URL.

Comments

The goal in parsing a URL is getting the list of its constituent parts ”such as scheme, domain, path , and so on. The parse_url() function will free you from having to write complicated regular expressions. Here's an example:

 $url = 'http://www.php.net/search.php?show=nosource&'; $url .= 'pattern=parse_url&sourceurl=http%3A%2F%2Fwww.php.net%2F'; $url_parts = parse_url ($url); 

$url_parts now is an associative array containing entries for

  • Scheme ” "http"

  • Host ” "www.php.net"

  • Path ” "/search.php"

  • Query ” "show=nosource&pattern=parse_url&sourceurl= http%3A%2F%2Fwww.php.net%2F"

parse_url() can also return "port" , " user " , "pass" , and "fragment" entries, depending on what kind of URL is passed.

But what if you want to turn the variables in the $url_parts["query"] query string into PHP variables? For that you can use parse_str() function:

 parse_str ($url_parts["query"]); // The current scope now contains variables $show, $pattern, and $sourceurl 

Gotcha

You do not need to use the parse_str() function on the query string of your script. PHP automatically converts a query string into PHP variables.




PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net