What are the best practices for handling HTTP requests in PHP to mimic a specific browser?

To mimic a specific browser when handling HTTP requests in PHP, you can set the User-Agent header to match that of the desired browser. This can be useful when scraping websites or accessing APIs that require a specific browser for compatibility.

$url = 'https://example.com';
$user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);

$response = curl_exec($ch);

if($response === false){
    echo 'Error: ' . curl_error($ch);
} else{
    echo $response;
}

curl_close($ch);