In website and mobile app development, understanding the user's terminal device information helps achieve better adaptation and optimization. Baidu provides a Mobile Terminal User Identification API that can retrieve the user's mobile brand, model, operating system, and more.
This article will demonstrate step by step how to use PHP to integrate this API and obtain user device information.
Before using Baidu services, you need to register a Baidu developer account. Visit the Baidu Developer website and follow the instructions to complete registration. Once registered, log in to the developer platform and create an application to obtain your API Key and Secret Key.
After creating the application, you can find the API Key and Secret Key in the application details. Keep these credentials safe as they will be used in your code.
Before coding, ensure your local PHP environment is installed and supports the curl extension. If not installed, you can run the following command:
sudo apt-get install php-curl
Create a file named device.php in your project directory and open it in a text editor.
First, include the Baidu Mobile Cloud SDK (download and extract it to your code directory) and include the autoload.php file:
require_once 'path/to/baidu-sdk-php/autoload.php';
Next, set the API Key and Secret Key:
$client = new BaiduDeviceClient('your_api_key', 'your_secret_key');Use the $client object to call the Baidu Mobile Terminal User Identification API:
$result = $client->identify(file_get_contents('http://your_website.com/your_image.jpg'));Replace the sample image URL with your actual image URL.
Retrieve user device information:
$deviceInfo = $result->getResult()->getUser(); echo 'Mobile Brand: ' . $deviceInfo->getBrand() . '<br>'; echo 'Mobile Model: ' . $deviceInfo->getModel() . '<br>'; echo 'Operating System: ' . $deviceInfo->getOs() . '<br>';
After saving the file, navigate to its directory in the command line and execute:
php device.php
If configured correctly, you will see the user's device information displayed in the command line.
Following these steps, you can use PHP to integrate the Baidu Mobile Terminal User Identification API and quickly retrieve users' mobile brand, model, and operating system information. This is very helpful for device adaptation and improving user experience for websites and mobile applications.