Monday, 16 July 2018

Get search query string from search engines using PHP

Get search query string from search engines using PHP

The search query string is normally passed as GET variables ‘q’ or ‘query’. The function below will return the search query string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Function returns the query string (q or query parameters) from the referrer
function get_search_query()
{
    $ref_keywords = '';
  
    // Get the referrer to the page
    $referrer = $_SERVER['HTTP_REFERER'];
    if (!empty($referrer))
    {
        //Parse the referrer URL
        $parts_url = parse_url($referrer);
 
        // Check if a query string exists
        $query = isset($parts_url['query']) ? $parts_url['query'] : '';
        if($query)
        {
            // Convert the query string into array
            parse_str($query, $parts_query);
            // Check if the parameters 'q' or 'query' exists, and if exists that is our search query terms.
            $ref_keywords = isset($parts_query['q']) ? $parts_query['q'] : (isset($parts_query['query']) ? $parts_query['query'] : '' );
        }
    }
    return $ref_keywords;
}
Note: Google has recently stopped sending the search query terms for all logged-in users. So, if a user is logged-in Google and searches for something and then follow a link to your site, you won’t be able to get the query terms that they searched for. The Making search more secure blog post by Google, explains this is more details.

0 comments:

Post a Comment