Using curl_errno() in PHP to Retrieve cURL Error Codes
This article explains the PHP curl_errno() function, detailing its definition, usage, and return values, provides a complete example showing how to initialize a cURL handle, execute a request, check for errors, retrieve error codes, and close the handle, and lists common cURL error codes.
When making network requests in PHP, errors such as timeouts or DNS failures can occur; the curl_errno() function allows developers to retrieve the error code of the most recent cURL operation.
1. Function Overview
The curl_errno() function accepts a cURL handle resource and returns the error number of the last request; it returns 0 if no error occurred.
int curl_errno ( resource $ch )2. Example Code
The following example demonstrates initializing a cURL handle, setting options, executing the request, checking for errors with curl_errno(), outputting either the error code or a success message, and finally closing the handle.
The script first creates a cURL handle and configures it, then runs curl_exec() to perform the request and stores the result in $response. Afterwards curl_errno() is called to determine whether an error occurred; if so, the error code is retrieved and displayed, otherwise a success message is printed. Finally curl_close() releases the handle.
3. Common Error Codes
Typical cURL error numbers and their meanings include:
1. CURLE_COULDNT_CONNECT (7): could not connect to host
2. CURLE_OPERATION_TIMEDOUT (28): operation timed out
3. CURLE_COULDNT_RESOLVE_HOST (6): could not resolve host
4. CURLE_SSL_CONNECT_ERROR (35): SSL connection error
5. CURLE_OK (0): no error
Conclusion
By using curl_errno() developers can easily obtain the error code of a cURL request, enabling more precise error handling and improving the stability and reliability of PHP 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.