Mastering PHP curl_errno(): Retrieve and Handle cURL Error Codes
Learn how to use PHP's curl_errno() function to obtain cURL request error codes, understand common error numbers, and implement robust error handling with practical code examples that initialize a cURL handle, execute requests, check for errors, and close the handle.
When making network requests, errors such as timeouts or DNS failures can occur. PHP provides the
curl_errno()function to retrieve the error code of a cURL request. This article introduces its usage and offers practical example code.
1. Function Overview
curl_errno()is a PHP function that returns the error code of the most recent cURL request. It accepts a cURL handle as its parameter and returns
0if no error occurred, otherwise a non‑zero error code.
<code>int curl_errno(resource $ch)</code>2. Example Code
The following example demonstrates using
curl_errno()to detect and handle errors.
<code><?php
// Initialize a cURL handle
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
// Get the error code
$error_code = curl_errno($ch);
echo "cURL request failed, error code: " . $error_code;
} else {
echo "cURL request succeeded!";
}
// Close the handle
curl_close($ch);
?>
</code>In this example we initialize a cURL handle, set options such as the request URL and whether to return the response, execute the request with
curl_exec(), and store the result in
$response. We then call
curl_errno()to check for errors; if an error occurred we retrieve the code with
curl_errno()and output a message. If no error occurred we output a success message. Finally,
curl_close()releases the handle.
3. Common Error Codes
Below are some common cURL error codes and their meanings:
CURLE_COULDNT_CONNECT (7): Unable to connect to the host.
CURLE_OPERATION_TIMEDOUT (28): Operation timed out.
CURLE_COULDNT_RESOLVE_HOST (6): Could not resolve host.
CURLE_SSL_CONNECT_ERROR (35): SSL connection error.
CURLE_OK (0): No error occurred.
Conclusion
By using the
curl_errno()function, developers can easily obtain the error code of a cURL request, allowing them to implement appropriate error handling strategies and improve the stability and reliability of their applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.