Simplest way to detect a mobile device in PHP

后端 未结 15 2333
别跟我提以往
别跟我提以往 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:39

    You could also use a third party api to do device detection via user agent string. One such service is www.useragentinfo.co. Just sign up and get your api token and below is how you get the device info via PHP:

    ";
    $url = "https://www.useragentinfo.co/api/v1/device/";
    
    $data = array('useragent' => $useragent);
    
    $headers = array();
    $headers[] = "Content-type: application/json";
    $headers[] = "Authorization: Token " . $token;
    
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    
    $json_response = curl_exec($curl);
    
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    
    if ($status != 200 ) {
        die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
    }
    
    curl_close($curl);
    
    echo $json_response;
    ?>
    

    And here is the sample response if the visitor is using an iPhone:

    {
      "device_type":"SmartPhone",
      "browser_version":"5.1",
      "os":"iOS",
      "os_version":"5.1",
      "device_brand":"Apple",
      "bot":false,
      "browser":"Mobile Safari",
      "device_model":"iPhone"
    }
    

提交回复
热议问题