How to set custom request headers (e.g., User-Agent) in a cURL request in PHP?

To set custom request headers, including the User-Agent header, in a cURL request in PHP, you can use the curl_setopt() function. Here's an example:

// Initialize cURL $ch = curl_init(); // Set the URL to send the request to curl_setopt($ch, CURLOPT_URL, 'http://example.com'); // Set the User-Agent header curl_setopt($ch, CURLOPT_USERAGENT, 'Custom User-Agent'); // Execute the request $response = curl_exec($ch); // Check for errors if ($response === false) { $error = curl_error($ch); // Handle error } // Close cURL curl_close($ch); // Process the response // ...

In the example above, curl_setopt() is used to set the CURLOPT_USERAGENT option to specify the custom User-Agent header ('Custom User-Agent') in the cURL request.

Note that you can set any other custom headers using curl_setopt() with the CURLOPT_HTTPHEADER option. The value for this option should be an array of header strings. For example:

// Set additional custom headers $headers = array( 'Header1: Value1', 'Header2: Value2', ); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

This allows you to set multiple custom headers if needed.