我正在检查不同URL上是否存在xml站点地图。如果我提供一个URL example.com/sitemap.xml,它有一个301指向www.example.com/sitemap.xml,我得到的显然是301。如果www.example.com/sitemap.xml不存在,我就看不到404。因此,如果我得到一个301,我将执行另一个cURL,看看404是否为www.example.com/sitemap.xml返回。但是,出于某种原因,我得到了随机的404和303状态码。
private function check_http_status($domain,$file){
$url = $domain . "/" . $file;
$curl = new Curl();
$curl->url = $url;
$curl->nobody = true;
$curl->userAgent = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.1) Gecko/20060601 Firefox/2.0.0.1 (Ubuntu-edgy)';
$curl->execute();
$retcode = $curl->httpCode();
if ($retcode == 301 || $retcode == 302){
$url = "www." . $domain . "/" . $file;
$curl = new Curl();
$curl->url = $url;
$curl->nobody = true;
$curl->userAgent = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.1) Gecko/20060601 Firefox/2.0.0.1 (Ubuntu-edgy)';
$curl->execute();
$retcode = $curl->httpCode();
}
return $retcode;
}发布于 2012-11-29 23:45:26
看看返回的响应代码列表- http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html。
通常web浏览器会自动处理这些问题,但是当您使用curl手动处理这些问题时,您需要了解每个响应的含义。301或302意味着您应该使用提供的替代url来访问资源。这可能是一个简单的添加到请求的www,但它也可能更复杂,因为重定向到不同的域also聚集。
303表示您正在使用POST尝试访问资源,应该使用GET。
发布于 2012-11-29 23:42:35
嗯,当你收到301或302时,你应该使用在响应中找到的位置,而不是假设另一个位置并尝试。
正如您在本例中看到的,来自服务器的响应包含文件的新位置。在您的下一个请求中使用它:http://en.wikipedia.org/wiki/HTTP_301#Example
发布于 2013-12-12 00:39:42
"followLocation“运行得很好。下面是我是如何实现它的:
$url = "http://www.YOURSITE.com//"; // Assign you url here.
$ch = curl_init(); // initialize curl.
curl_setopt($ch, CURLOPT_URL, $url); // Pass the URL as the option/target.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 0 will print html. 1 does not.
curl_setopt($ch, CURLOPT_HEADER, 0); // Please curl, inlude the header in the output.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // ..and yes, follow what the server sends as part of the HTTP header.
$response_data = curl_exec($ch); // execute curl with the target URL.
$http_header = curl_getinfo($ch); // Gets information about the last transfer i.e. our URL
// Print the URLs that are not returning 200 Found.
if($http_header['http_code'] != "200") {
echo " <b> PAGE NOT FOUND => </b>"; print $http_header['http_code'];
}
// print $http_header['url']; // Print the URL sent back in the header. This will print the page to wich you were redirected.
print $url; // this will print the original URLs that you are trying to access
curl_close($ch); // we are done with curl; so let's close it.https://stackoverflow.com/questions/13629261
复制相似问题