PHP

PHP Device Detection: Effectively Classifying Smartphones, Feature Phones, Carriers, and Browsers

Nowadays, you rarely see websites specifically for feature phones, but in the past, it was necessary to change content based on different devices like smartphones, feature phones, and even carriers and browsers.
This time, I’ll introduce how to detect these devices using PHP.
By the way, this method can also be achieved using JavaScript or .htaccess.

PHP Code to Detect Devices

<?php
$docomo = "/docomo/";		//DoCoMo
$au = "/au/";			//au
$softbank = "/sb/";		//SoftBank
$msie = "/index.html";		//IE
$Netscape = "/index.html";	//Netscape
$opera = "/index.html";		//Opera
$firefox = "/index.html";	//Firefox
$pc = "/index.html";		//Other browsers
$mobile = "/sp/";		//iPhone

if(isset($_SERVER['HTTP_USER_AGENT'])){
	$user_agent = $_SERVER['HTTP_USER_AGENT'];
	if(eregi("DoCoMo",$user_agent)){header("Location: $docomo");}
	elseif(eregi("UP\.Browser",$user_agent)){header("Location: $au");}
	elseif(eregi("J-PHONE",$user_agent)){header("Location: $softbank");}
	elseif(eregi("Vodafone",$user_agent)){header("Location: $softbank");}
	elseif(eregi("SoftBank",$user_agent)){header("Location: $softbank");}
	elseif(eregi("J-EMULATOR",$user_agent)){header("Location: $softbank");}
	elseif(eregi("MSIE",$user_agent)){header("Location: $msie");}
	elseif(eregi("Netscape",$user_agent)){header("Location: $netscape");}
	elseif(eregi("Opera",$user_agent)){header("Location: $opera");}
	elseif(eregi("Firefox",$user_agent)){header("Location: $firefox");}
	elseif(eregi("iPhone",$user_agent)){header("Location: $mobile");}
	else{header("Location: $pc");}
}else{
	header("Location: $pc");
}
?>

By placing the above headers, you can classify pages by smartphones, feature phones, carriers, and browsers.

Using this code, you can detect the type of device a user is accessing with and redirect them to the appropriate page.

Summary

Device detection using PHP is an old technique, but there are still situations where it can be useful. These days, responsive design allows you to not worry too much about the display differences across devices, but if you want to provide a page optimized for specific devices, this method can be helpful.

 
※ Please use this code at your own discretion.