How to set a timeout for a cURL request in PHP?

To set a timeout for a cURL request in PHP, you can use the CURLOPT_TIMEOUT option. Here's an example:

// Create a cURL handle $ch = curl_init(); // Set the URL curl_setopt($ch, CURLOPT_URL, "http://example.com"); // Set the timeout in seconds curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Execute the request $response = curl_exec($ch); // Check for errors if ($response === false) { echo "cURL Error: " . curl_error($ch); } // Close the cURL handle curl_close($ch);

In the above example, curl_setopt() is used to set the CURLOPT_TIMEOUT option to 10 seconds. This means that if the request takes longer than 10 seconds to complete, it will time out. You can adjust the timeout value as per your requirement.

Please note that the CURLOPT_TIMEOUT option sets the timeout for the entire request, including any redirects or waiting for a response. If you want to set a separate timeout for the connection phase, you can use the CURLOPT_CONNECTTIMEOUT option instead.