Simple Server Response Checker With PHP and cURL

By | May 8, 2008

I often need to check website lists for error codes (yesterday I’ve told you about 4XX codes). There is a simple solution written in PHP that allows to d this. You need cURL support enabled (please, let me know if I need to describe cuRL installation process on my blog) and that’s all. Here is the code:

<?
// A simple function that allows to extract the value between two parts of a string
function extract_value($source, $start, $end)
{
$pos=@strpos($source, $start)+strlen(stripslashes($start));
$pos2=@strpos($source, $end, $pos);
$len=$pos2-$pos;
$output=substr($source, $pos, $len);
return $output;
}

// Let’s open the file with links in the following format <a href=URL>ANCHOR</a>
$sd=fopen("links.txt", "r");

$add=fopen(“links_good.txt”, “a”);

do
{
flush();

$lin=fgets($sd);
// Getting the URL value
$url=trim(extract_value($lin, “href=”, “>”));
echo $url;

//Starting cURL Session
$ch=curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
// Getting headers only (They include server response)
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
// Getting server output to a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$content=curl_exec($ch);
curl_close($ch);

// Getting the first line of server response
$main=substr($content, 0, strpos($content, “n”));

// If it doesn’contain 200, or any other code you need (Maybe 302)
if (!substr_count($main, “200”))
{
echo ” BAD”;
}
else
{

echo ” OK”;
fwrite($add, trim($lin).”rn”);
}

echo “rn”;
}
while (!feof($sd));

fclose($add);

?>