我想使用 cURL 发送请求并检索响应标头。
使用浏览器,响应头如下:
HTTP/1.0 302 Moved Temporarily
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache
Location: "Correct URL"
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Tue, 30 Oct 2012 08:32:24 GMT
Server: Google Frontend
Content-Length: 0
但是当我使用 cURL 发送请求时,响应头如下:
HTTP/1.1 302 Found
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache
Location: "Wrong URL"
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Tue, 30 Oct 2012 09:12:14 GMT
Server: Google Frontend
Content-Length: 0
我想知道是什么导致响应返回不同的 URL。这是我尝试但无济于事的许多示例和事情中的一个小型 php 示例。
<?php
$url = "url";
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_HEADER, true );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );
curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.4) Gecko/20091030 Gentoo Firefox/3.5.4" );
list( $header, $contents ) = preg_split( '/([\r\n][\r\n])\\1/', curl_exec( $ch ), 2 );
curl_close( $ch );
$header_text = preg_split( '/[\r\n]+/', $header );
foreach ( $header_text as $headers ) {
echo $headers . "</br>";
}
?>