Detecting Search Engine Bots with PHP
In web development, it may often be necessary to identify the source of traffic to your website. One common task is detecting search engine bots, also known as crawlers or spiders.
Solution
To detect search engine bots using PHP, you can analyze the HTTP user agent string sent by the browser. Here's a commonly used approach:
function _bot_detected() { return (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT'])); }
This code checks if the HTTP user agent string (e.g., "Googlebot") contains specific keywords commonly associated with search engine bots. It returns true if a bot is detected, otherwise false.
Recent Update
Note that the user agent string for Google bots has recently changed. As of June 16, 2017, it includes the term "mediapartners." This has been incorporated into the regular expression used in the code above to ensure accurate detection.
The above is the detailed content of How Can I Detect Search Engine Bots Using PHP?. For more information, please follow other related articles on the PHP Chinese website!