Question

I want to use the query that someone used to find my page, these are in the URL of the referring page $GET_['q'] (and for yahoo $GET_['p']). How can I use these? I want something like $query = REFERRING PAGE ($GET_['q']), but I just can't figure out the way to say it.

Was it helpful?

Solution

The information you are searching for is available in $_SERVER['HTTP_REFERER']

For instance, coming from a page with this URL : http://tests/temp/temp-2.php?q=test+glop, this portion of code :

var_dump($_SERVER['HTTP_REFERER']);

Gives :

string 'http://tests/temp/temp-2.php?q=test+glop' (length=40)


You can the use parse_url to get the query string from that URL :

$query = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY);
var_dump($query);

will get you :

string 'q=test+glop' (length=11)


Now, you can parse that query string with parse_str ; this code :

$params = array();
parse_str($query, $params);
var_dump($params);

Will get you :

array
  'q' => string 'test glop' (length=9)


And, finally, you can check whether the parameter that interests you is in that array :

if (isset($params['q'])) {
    var_dump($params['q']);
}

Will give us, in this example :

string 'test glop' (length=9)


Et voila ;-)

Just note that the Referer is sent by the client, which means :

  • it can be forged, and can contain anything -- including bad stuff (beware SQL injections and XSS !)
  • it is optionnal : the browser is not required to send it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top