我有一个php脚本,我最近添加了一个数组。php脚本从数组中检查URL是否有一组文本也在数组中。一切都很好,除了脚本不会遵循重定向或检查子页面。有人告诉我,这是fsocketopen的限制,我需要使用CURL。如果是这种情况,那么我需要一些帮助将其从使用fsocketopen转换为CURL。希望有一些方法可以让fsocketopen遵循重定向或至少访问子页面。
function check($host, $find){
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp){
echo "$errstr ($errno)'n";
} else {
$header = "GET / HTTP/1.1'r'n";
$header .= "Host: $host'r'n";
$header .= "Connection: close'r'n'r'n";
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);
显然我没有把问题讲清楚。我正在寻找确认fsocketopen不能遵循重定向或它不能转到子页面(url.com/subpage)。如果是这样的话,CURL是我最好的选择吗?有什么例子可以参考吗?
当您获得从feof()
返回的数据时,您可以从标题中解析出重定向信息并创建连接,但这有点烦人,cURL
自行完成。
你应该能够使用
$ch = curl_init($host);
curl_setopt_array($ch, array(
CURLOPT_RETUNTRANSFER => true
, CURLOPT_FOLLOWLOCATION => true
, CURLOPT_HEADER => true
));
$str = curl_exec($ch);
cURL
默认使用Location:
头遵循重定向