I have a simple cURL script that works just fine.
But I’m curious about how to detect a bad Url. And by “bad” I mean a non-existant URL, or if the server I am calling is down for a period of time, or I made a mistake and entered the wrong URL. (just examples)
here’s what I have so far:
<?php
$url = 'http://someurl_or_ip.com/some_file.php';
$post_fields = "type=whatever";
$post_fields .= "&first=".$first;
$post_fields .= "&last=".$last;
$ch = curl_init($url); // create a new cURL resource
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 1800);
// Execute the request.
$raw_response = curl_exec($ch);
$succeeded = curl_errno($ch) == 0 ? true : false;
echo $raw_response;
?>
typically the $raw_response is something I can parse and use for other things, like how I want to display data to a user.
I simply replaced $url with a non-existent file (but to a valid domain), and I get “Not Found….The requested URL…..was not found on this server…”
Does this mean I need to parse this apache server message to know it’s not a good URL? Or does cURL have a way to detect it, via header information?
You can look at the HTTP response code in the header, which will be 404 for a file not found:
If the server is not available, you obviously won’t get a response from the server at all, thus no HTTP response code. In this case
curl_exec()would return with false, in which case you can handle the error: