Last active
November 29, 2018 09:13
-
-
Save jonoalderson/fe991405f02acc5beb60a8418deb64ac to your computer and use it in GitHub Desktop.
Looks up the user agent against a known list, and outputs a HTML comment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Quick script to check and output the user agent in a HTML comment | |
// Jono Alderson [https://www.jonoalderson.com] | |
// ================================= | |
// Google user agent strings are sourced from | |
// [https://support.google.com/webmasters/answer/1061943?hl=en] | |
// Feel free to add/edit definitions | |
// ================================= | |
// Last updated: 20/03/2018 | |
// Housekeeping & setup | |
// ================================= | |
if (!isset($_SERVER) || empty($_SERVER)) { return false; } | |
if (!isset($_SERVER["HTTP_USER_AGENT"]) || $_SERVER["HTTP_USER_AGENT"] == false) { return false; } | |
$userAgent = $_SERVER["HTTP_USER_AGENT"]; | |
$userAgents = array( | |
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" => "Google (Desktop)", | |
"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" => "Google (Mobile)" | |
); | |
// Check if the string matches a known agent | |
// ================================= | |
if (in_array($userAgent,$userAgents)) { | |
$userAgentString = $userAgents[$userAgent]; | |
} else { | |
$userAgentSanitized = htmlspecialchars($userAgent); | |
$userAgentSanitized = str_replace(array("-->","<!--"), "", $userAgentSanitized); | |
$userAgentString = "OTHER - " . $userAgentSanitized; | |
} | |
// Construct the comment | |
// ================================= | |
$date = date('r'); | |
$comment = "<!-- " . PHP_EOL; | |
$comment .= "User agent: {$userAgentString}" . PHP_EOL; | |
$comment .= "Time: " . $date . PHP_EOL; | |
$comment .= "-->". PHP_EOL; | |
echo $comment; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do I use this code please ?