How does google handle two same URL parameters wit

2019-09-16 15:44发布

问题:

Just take a look at this url, and you will know what I mean.

https://www.google.com/search?q=site%3Aphpjs.org&q=date

And when I go to that url, the search term in google's search bar is site:phpjs.org date.

How does Google 'morph' the two parameters together, and how would one do it in PHP?

回答1:

Instead of encoding the space, Google uses the same q variable to accomplish the same thing.

Unfortunately, PHP doesn't have the built-in ability to do this, because successive occurrences of the same query string parameter will overwrite the first one, unless the [] suffix is used.

You would need something like this:

$params = array();
foreach (explode('&', $_SERVER['QUERY_STRING']) as $param) {
    list($name, $value) = explode('=', $param, 2);
    $params[] = array(urldecode($name) => urldecode($value));
}

Contents of $params:

array(
    array('q' => 'site:phpjs.org'),
    array('q' => 'date'),
);

Alternatively, you can change the loop body to this:

$params[urldecode($name)][] = urldecode($value);

That will change $params to:

array('q' => array('site:phpjs.org', 'date'));

Which will make it easier to just do:

join(' ', $params['q']);
// "site:phpjs.org date"


回答2:

It will always use the last variable's value in the provided url. This is more of a standard way, and it isn't just Google that handles it this way. You can try it yourself by creating a page named index.php in your root directory. Then access the page via http://example.com/index.php?q=John&q=Billy. Inside index.php add this: <?php echo $_GET['q']; ?>.

So what happens is that the last value is used, except that google strips the URL and concats the variables' values together. I hope it makes sense!



标签: php get