When sharing one of my pages on FB, I want to display something different. Problem is, I prefer not to use the og: elements, but to recognize FB user-agent.
What is
"Facebook's user-agent string is facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)..."
Hi
Small, yet important, correction -> Facebook external hit uses 2 different user agents:
facebookexternalhit/1.0 (+http://www.facebook.com/externalhit_uatext.php)
facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)
Setting you fitler to 1.1 only may cause filtering issues with 1.0 version.
For more information about Facebook Bot (and other bots) please refer to Botopedia.org - a Comunity-Sourced bot directory, powered by Incapsula.
Besides user-agent data, the directory also offers an IP verification option, allowing you to cross-verify an IP/User-Agent, thus helping to prevent impersonation attempts.
For list of user-agent strings, look up here. The most used, as of September 2015, are facebookexternalhit/*
and Facebot
. As you haven't stated what language you're trying to recognize the user-agent in, I can't tell you more information. If you do want to recognize Facebook bot in PHP, use
if (
strpos($_SERVER["HTTP_USER_AGENT"], "facebookexternalhit/") !== false ||
strpos($_SERVER["HTTP_USER_AGENT"], "Facebot") !== false
) {
// it is probably Facebook's bot
}
else {
// that is not Facebook
}
UPDATE: Facebook has added Facebot
to list of their possible user-agent strings, so I've updated my code to reflect the change. Also, code is now more predictible to possible future changes.
You already have the answer for Facebook above, but one way to get any user agent is to place a script on your site that will mail you when there is a visit to it. For example, create this file on your domain at, say, https://example.com/user-agent.php :
<?php
mail('you@youremail.com', 'User Agent', $_SERVER['HTTP_USER_AGENT']);
Then, visit Facebook, and type the link to the script there, and hit space bar. You don't actually have to share anything, just typing the link in and a space will cause Facebook to fetch a preview. You should then get an email with Facebook's user agent.
Please do note that sometimes the agent is visionutils/0.2
. You should check for it too.
In the perspective of user-agent modifications on FB side, it is maybe safer to use a regex like that :
<?php
if (preg_match("/facebook|facebot/i", $_SERVER['HTTP_USER_AGENT'])){
do_something();
}
?>
You can find more information about Facebook crawler on their doc: https://developers.facebook.com/docs/sharing/webmasters/crawler