PHP Detects Mobile Devices (PDMD)

You may need to detect mobile devices in PHP based websites in your project.

You may see many websites that have a desktop version as well as a simplified mobile version of the same website to make it easier for mobile internet users. But to do so you have to detect mobile devices.

Detecting mobile devices from the server side is the best because it will not load unnecessary content and actually makes the website faster by only loading the content you want to display on mobile devices.

While you can use CSS media queries, it won't prevent mobile devices from loading content that you want only for computers or desktops.

So the best way to detect mobile devices from the server side. You can do it using PHP. In this tutorial, I will show you a simple PHP code snippet that will easily detect if a visitor on your site is using a mobile device.

Belo is a simple PHP code that can be used to detect mobile devices:

function isMobileDevice() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

How to use the above PHP code snippet?

Once you place the code above you can use it like the code below:

if(isMobileDevice()){
    //Your content or code for mobile devices goes here
}
else {
    //Your content or code for desktop or computers devices
}

Below is the complete code that you can test on mobile and desktop:

<?php
function isMobileDevice() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}
if(isMobileDevice()){
    echo "It is a mobile device";
}
else {
    echo "It is desktop or computer device";
}
?>

Now test the above code. If you test it with your mobile device then you will see the text “ This is a mobile device “. And when you test it with your PC or desktop then you will see the text “ This is a desktop or computer device “.

So how is it? Isn't this a great and easy way to detect mobile devices and implement if-else conditional statements?

Now if you can detect mobile devices in PHP then you can also detect desktop by simply using if else statement again. In the above code what you can see in the else section is for desktop devices.


Post a Comment

Previous Next

نموذج الاتصال