PHP’s cURL functions are extremely useful for sending HTTP requests.
Some examples of its usefulness.
- Retrieving data from an external API.
- Sending data to an external web service.
- Checking to see if a HTTP resource exists.
- Crawling / scraping web pages (logging into other websites with PHP).
Although you can easily request external content via the function file_get_contents, cURL is much more useful in the sense that it allows us to detect and handle certain HTTP errors.
Let’s take the following example.
$url = 'http://example.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); echo $result;
As you can see, we have setup a very simple GET request that returns the contents of a website called example.com.
Unfortunately, this code doesn’t take into account the fact that the cURL request could fail. As a result, the request might fail without providing us with any details about what happened.
Using curl_errno to detect cURL errors.
This is where the curl_errno function comes in handy.
The curl_errno function will return the number 0 (zero) if the request was successful. In other words, it will return a “falsey” value if no error occurs. This is because PHP sees 0 as a false value in a boolean context.
This allows us to figure out whether or not our cURL request resulted in an error.
Take a look at the following example.
$url = 'http://example.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); if(curl_errno($ch)){ echo 'Request Error:' . curl_error($ch); }
If an error occurs, then our script will print out the result of the curl_error function.
Throwing Exceptions.
In certain situations, you might want to throw an exception if a cURL request fails.
For this example, let us pretend that we have an object function called get.
/** * Send a GET request to a URL. * * @param string $url * @return string * @throws Exception If cURL request fails. */ public function get($url){ $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); if(curl_errno($ch)){ throw new Exception(curl_error($ch)); } return $result; }
As you can see, the function above will attempt to send a GET request to a given URL.
If all goes well, the function will return the contents of the URL.
However, if the request fails and a cURL error exists, PHP will throw an Exception.
This allows us to handle the request like so.
try{ $object->get('http://test.com'); } catch(Exception $e){ //do something with the exception you caught }
In the above piece of code, we are using a TRY-CATCH block.
If we do not want our application to continue after a failed HTTP request, we can omit the TRY-CATCH block and let our Exception Handler deal with it.