Check if user agent is bot in PHP

if ( ! function_exists( 'is_bot' ) ) {
	/**
	 * is_bot.
	 */
	function is_bot() {
		$bots = array(
			'Google-Structured-Data-Testing-Tool',
			'bot',
			'crawl',
			'slurp',
			'spider',
		);
		$bots = '/' . implode( '|', $bots ). '/i';
		// For faster execution instead of array and implode use:
		// $bots = '/Google-Structured-Data-Testing-Tool|bot|crawl|slurp|spider/i';
		return ( isset( $_SERVER['HTTP_USER_AGENT'] ) && preg_match( $bots, $_SERVER['HTTP_USER_AGENT'] ) );
	}
}

Leave a Comment