Home >Backend Development >PHP Tutorial >How to get inbound search engines and keywords with PHP_PHP Tutorial
Sometimes, when we enter a website from a search engine, there will be a line of small text, "Welcome from Google/Baidu, come to this site by searching for the "XXX" keyword" or something like that. So how is this function implemented? In fact, it's not difficult. The general idea is to get the inbound URL and then regularize the data we need.
<?php $url=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'';//获取入站url。 $search_1 = "google.com"; //q= $search_2 = "baidu.com"; //wd= $google = preg_match("/\b{$search_1}\b/",$url);//记录匹配情况,用于入站判断。 $baidu = preg_match("/\b{$search_2}\b/",$url); $s_s_keyword=""; if ($google) { //来自google $s_s_keyword=get_keyword($url,'q=');//关键词前的字符为“q=”。 $s_s_keyword=urldecode($s_s_keyword); //$s_s_keyword=iconv("GBK","UTF-8",$s_s_keyword);//引擎为gbk } else if($baidu) { //来自百度 $s_s_keyword=get_keyword($url,'wd=');//关键词前的字符为“wd=”。 $s_s_keyword=urldecode($s_s_keyword); $s_s_keyword=iconv("GBK","UTF-8",$s_s_keyword);//引擎为gbk } echo '$s_s_keyword'; /* 获取来自搜索引擎入站时的关键词。 */ // 函数作用:从url中提取关键词。参数说明:url及关键词前的字符。 function get_keyword($url,$kw_start) { $start=stripos($url,$kw_start); $url=substr($url,$start+strlen($kw_start)); $start=stripos($url,'&'); if ($start>0) { $start=stripos($url,'&'); $s_s_keyword=substr($url,0,$start); } else { $s_s_keyword=substr($url,0); } return $s_s_keyword; } ?>