Simplest way to detect a mobile device in PHP

后端 未结 15 2350
别跟我提以往
别跟我提以往 2020-11-22 05:12

What is the simplest way to tell if a user is using a mobile device to browse my site using PHP?

I have come across many classes that you can use but I was hoping fo

15条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:40

    I wrote this script to detect a mobile browser in PHP.

    The code detects a user based on the user-agent string by preg_match()ing words that are found in only mobile devices user-agent strings after hundreds of tests. It has 100% accuracy on all current mobile devices and I'm currently updating it to support more mobile devices as they come out. The code is called isMobile and is as follows:

    function isMobile() {
        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"]);
    }
    

    You can use it like this:

    // Use the function
    if(isMobile()){
        // Do something for only mobile users
    }
    else {
        // Do something for only desktop users
    }
    

    To redirect a user to your mobile site, I would do this:

    // Create the function, so you can use it
    function isMobile() {
        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 the user is on a mobile device, redirect them
    if(isMobile()){
        header("Location: http://m.yoursite.com/");
    }
    

    Let me know if you have any questions and good luck!

提交回复
热议问题