我使用函数file_get_contents从网页获取内容。有些网站工作得很好,但大多数都给我这个错误
failed to open stream: HTTP request failed! HTTP/1.1 503 Service Temporarily Unavailable
下面是我的简单代码
echo file_get_contents("url");
当我在浏览器中运行此url时,它工作正常。有什么问题吗?
503表示功能正在工作,并且您正在从远程服务器获得拒绝您的响应。如果您曾经尝试cURL google结果,也会发生同样的事情,因为它们可以检测file_get_contents和cURL使用的用户代理,从而阻止这些用户代理。也有可能你正在访问的服务器也有它的IP地址黑名单。
主要有三个常见的原因导致命令在远程环境下不能像浏览器一样工作。
1) The default USER-AGENT has been blocked.
2) Your server's IP block has been blocked.
3) Remote host has a proxy detection.
使用这个脚本,大多数网站认为你是一个浏览器:
<?php
getWebsite('http://mywebsite.com');
function getWebsite($url='http://mywebsite.com'){
$ch = curl_init();
$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/'.rand(8,100).'.0';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,CURL_SSLVERSION_DEFAULT);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$webcontent= curl_exec ($ch);
$error = curl_error($ch);
curl_close ($ch);
return $webcontent;
}
?>