Parse URL in php

2019-09-08 16:41发布

In php, if I wanted to parse a URL, such as www.site.com/index.php?foo=bar, I can do with the _POST variable. I can retrieve bar by _POST['foo'].

But what if my URL is something like www.site.com/index.php?foo&bar. i.e., I don't have the arguments as key-value pairs as in the first case. How to parse this in php?

标签: php url
2条回答
祖国的老花朵
2楼-- · 2019-09-08 17:15

Use parse_url.

Quoted from php.net:

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

This function is not meant 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.

Then, use parse_str function to parse the query parameters part.

Parses str as if it were the query string passed via a URL and sets variables in the current scope. To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from external sources. The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.

<?php 
  $parts = parse_url('www.site.com/index.php?foo&bar');
  print_r($parts);
  // Array ( [path] => www.site.com/index.php [query] => foo&bar )


  parse_str ($parts['query'], $query);
  print_r($query);
  // Array ( [foo] => [bar] => ) 

 // Alternately you can do this in a single shot like below:
 parse_str(parse_url('www.site.com/index.php?foo&bar', PHP_URL_QUERY));

?>
查看更多
beautiful°
3楼-- · 2019-09-08 17:28

It's a misconception that requesting a URL like

http://www.example.com/index.php?foo=bar

would give you bar in $_POST['bar']. Url parameters will populate $_GET. Anything that's supposed to show up in $_POST has to be submitted in the Request body. See How are parameters sent in an HTTP POST request? for some details.

With that clarified, empty URL parameters are not a problem at all. A URL like

http://www.example.com/index.php?foo&bar

will populate $_GET['foo'] and $_GET['bar'] with empty values.

查看更多
登录 后发表回答