Skip to content

Instantly share code, notes, and snippets.

@jonoalderson
Last active November 29, 2018 09:13
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonoalderson/fe991405f02acc5beb60a8418deb64ac to your computer and use it in GitHub Desktop.
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
<?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;
@mumore7
Copy link

mumore7 commented Mar 25, 2018

How do I use this code please ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment