I have a php script that I recently added an array to. The php script checks URL's from the array for a set of text also in the array. Everything works great except the script will not follow redirects or check sub-pages. I have been told that this is a limitation of fsocketopen and that I need to use CURL. If this is the case then I require some assistance converting this from using fsocketopen to CURL. Hopefully there is some way to get fsocketopen to follow redirects or at least access sub-pages.
function check($host, $find){
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp){
echo "$errstr ($errno)
";
} else {
$header = "GET / HTTP/1.1
";
$header .= "Host: $host
";
$header .= "Connection: close
";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host){
$headers = 'From: Set your from address here';
mail('my-email@my-domain.com', 'Website Monitoring', $host.' is down' $headers);
}
$hostMap = array(
'www.my-domain.com' => 'content on site',
'www.my-domain2.com' => 'content on second site',
);
//if (!check($host, $find)) alert($host);
foreach ($hostMap as $host => $find){
if( !check( $host, $find ) ){
alert($host);
}
}
unset($host);
unset($find);
Apparently I wasn't clear in my question. I am looking for confirmation that fsocketopen cannot follow redirects or that it cannot go to a sub-page (url.com/subpage). If this is the case, is CURL my best option and are there any examples I can look at?
When you get the data returned from feof()
, you can parse out the redirect information from the headers and create connect to that, but that is kind of annoying and cURL
does it on its own.
You should just be able to use
$ch = curl_init($host);
curl_setopt_array($ch, array(
CURLOPT_RETUNTRANSFER => true
, CURLOPT_FOLLOWLOCATION => true
, CURLOPT_HEADER => true
));
$str = curl_exec($ch);
cURL
follows redirects by default using the Location:
header.