In my PHP page I should display two different text contents according to whether the page run under mobile or desktop browser. Is there a way to perform this control in PHP?
An easy way to detect a mobile or desktop device in PHP is to check if the HTTP user agent contains the word “mobile”. $ua = strtolower($_SERVER["HTTP_USER_AGENT"]); $isMob = is_numeric(strpos($ua, "mobile"));
Use HTTP_USER_AGENT and the preg_match() Function to Detect Mobile Devices in PHP. For example, create a variable $user_agent and store $_SERVER["HTTP_USER_AGENT"] in it. Then use the preg_match() function to match the user-agent string. Use the collection of strings as the first parameter.
There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net
Using that it's quite easy to only display content for a mobile:
include 'Mobile_Detect.php'; $detect = new Mobile_Detect(); // Check for any mobile device. if ($detect->isMobile()){ // mobile content } else { // other content for desktops }
I used Robert Lee`s answer and it works great! Just writing down the complete function i'm using:
function isMobileDevice(){ $aMobileUA = array( '/iphone/i' => 'iPhone', '/ipod/i' => 'iPod', '/ipad/i' => 'iPad', '/android/i' => 'Android', '/blackberry/i' => 'BlackBerry', '/webos/i' => 'Mobile' ); //Return true if Mobile User Agent is detected foreach($aMobileUA as $sMobileKey => $sMobileOS){ if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){ return true; } } //Otherwise return false.. return false; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With