Skip to content

Instantly share code, notes, and snippets.

@dsager
Last active August 29, 2015 14:05
Show Gist options
  • Save dsager/232b9b159f0eef3b5a91 to your computer and use it in GitHub Desktop.
Save dsager/232b9b159f0eef3b5a91 to your computer and use it in GitHub Desktop.
Some PHP functions to detect if a UA is mobile/tablet
<?php
/**
* Inspired by the neat Browser Gem for Ruby: https://github.com/fnando/browser
*
* Copyright (c) 2014 Daniel Sager
* License: https://gist.github.com/dsager/0edcbf806b5b86e78455#file-2014
*/
/**
* @param null|string $ua
* @return bool
*/
function is_tablet($ua = null) {
if (is_null($ua)) $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('/ipad/', $ua)) return true;
if (preg_match('/touch/', $ua) && preg_match('/windows nt 6.[2-3]/', $ua) && preg_match('/arm/', $ua)) return true;
if (!is_phone($ua) && preg_match('/android/', $ua) && !preg_match('/opera|opr/', $ua)) return true;
if (preg_match('/playbook/', $ua) && preg_match('/rim tablet/', $ua)) return true;
return false;
}
/**
* @param null|string $ua
* @return bool
*/
function is_phone($ua = null) {
if (is_null($ua)) $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('/opera mini/', $ua)) return true;
if (preg_match('/blackberry/', $ua)) return true;
if (preg_match('/(mobi(le)?|symbian|midp|windows ce|windows phone)/', $ua)) return true;
if (preg_match('/(psp|playstation vita)/', $ua)) return true;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment