tags:

views:

103

answers:

1

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.

+2  A: 

Hi,

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.
Pascal MARTIN
+1: Excellent answer. It's also worth pointing out that yes, it really is spelled "referer" in the context of HTTP. 8-)
RichieHindle
Thanks ! Ergh, reading your comment, I first though "oh, did I spell it wrong ?" ^^ One more funny thing in our daily job ^^
Pascal MARTIN
I'm afraid I don't follow. If I say: $query = $_SERVER['HTTP_REFERER'];then $query = the full google address. If I say:$query = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY);var_dump($query);Then $query has no value. Do I need to include the var_dumps or are those just for my education while?
pg
pg
@pg: this could be due to the fact that, as Pascal pointed out, the referer header is optionally sent. If the header is not sent by the client (browser) then there is nothing to extract. And yes, var_dump is mainly used for debugging / testing purposes.
fireeyedboy
pg
@pg : maybe you could find out some regex that might work, yes ; but why use a regex when PHP provides functions that have been created to deal with URLs and extraction of the informations that compose them ? ;; yes, the var_dump is just a nice way to display content of variables, which gets more informations that echo, for instance.
Pascal MARTIN