get a random user agent in php

To get a random user agent in PHP, you can use the cURL library to make HTTP requests with headers that contain the user agent. Here is an example code snippet:

main.php
<?php
// array of user agents to choose from
$userAgents = array(
    'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:77.0) Gecko/20190101 Firefox/77.0',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
    'Mozilla/5.0 (Android 11; Mobile; rv:68.0) Gecko/68.0 Firefox/81.0',
    // add more user agents here
);

// choose a random user agent from the array
$randomUserAgent = $userAgents[array_rand($userAgents)];

// make a cURL request with the chosen user agent
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $randomUserAgent);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
$response = curl_exec($ch);
curl_close($ch);

// do something with the response
echo $response;
?>
807 chars
24 lines

In this example, we define an array of user agents to choose from, then we use the array_rand function to choose a random user agent from the array. We then make a cURL request with the chosen user agent and the CURLOPT_USERAGENT option, and we store the response in the $response variable. Finally, we can do something with the response, such as echoing it to the screen.

gistlibby LogSnag