When making network requests, developers often encounter various errors, such as connection timeouts, DNS resolution failures, and more. To effectively handle these errors, PHP provides a very useful function—curl_errno(), which helps developers retrieve the error codes for cURL requests. This article will explain how to use the curl_errno() function and provide example code.
curl_errno() is a PHP function that retrieves the error code from the most recent cURL request. Its definition is as follows:
int curl_errno ( resource $ch )
This function accepts a cURL handle as its parameter and returns the error code for the most recent cURL request. If no error occurred, it returns 0; if an error occurred, it returns a non-zero error code.
Below is an example that demonstrates how to use the curl_errno() function to check and retrieve error codes from a cURL request:
<?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 cURL request
$response = curl_exec($ch);
// Check if any error occurred
if(curl_errno($ch)){
// Get the error code
$error_code = curl_errno($ch);
echo "cURL request failed with error code: " . $error_code;
} else {
echo "cURL request succeeded!";
}
// Close the cURL handle
curl_close($ch);
?>
In the above example, we first initialize a cURL handle and set various cURL options (such as the requested URL and whether to return the response content). We then execute the cURL request using the curl_exec() function and store the result in the $response variable.
Next, we use the curl_errno() function to check whether any errors occurred. If an error occurred, we retrieve the error code and display an error message; otherwise, we output "cURL request succeeded!".
Finally, we close the cURL handle using curl_close() to release resources.
Here are some common cURL error codes and their meanings:
These error codes help developers diagnose and address various issues that may arise with cURL requests, improving the reliability and stability of applications.
By using the curl_errno() function, developers can easily retrieve error codes from cURL requests and handle errors accordingly. This feature plays a crucial role in optimizing the reliability and stability of network requests in real-world development.
We hope this article has helped you understand and use the curl_errno() function effectively, and provided useful insights for your development projects!