How to Check If a Visitor to your Website is from a Mobile or PC in PHP?

Updated on September 2, 2017

Ever want to check if a particular visitor to your website is from a mobile device or desktop using PHP? then here’s how you can do that. $_SERVER in PHP, a super global variable or an array that contains information about the server’s hostname, remote IP address, HTTP user agent, script locations, commandline arguments, web server details etc…It means, we are just going to use $_SERVER array to find the HTTP_USER_AGENT of a visitor. To do that, let’s create a simple function named ‘is_mobile‘ and use ‘preg_match‘ to check for the patterns such as iPhone, Android, Mobile, Windows Phone etc…and return true upon match.

Create a function is_mobile as below:

php $_SERVER tutorial

function is_mobile() {
 if (preg_match("/Mobile|Android|BlackBerry|iPhone|Windows Phone/", $_SERVER['HTTP_USER_AGENT'])) {
 return true;
 }
 }

Now, in a IF cond:

if(is_mobile())
 {
 //Mobile specific code
 }
if(!is_mobile())
 {
 //Desktop specific code
 }

Using WordPress? You can simply copy and paste is_mobile() into ‘functions.php‘ file and call it from anywhere inside the WordPress directory.

Was this article helpful?

Related Articles

Leave a Comment