Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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