[英]How can I get HTTP headers (Location) from some URL?
我有一些地址(例如: http : //example.com/b-out/3456/3212/)。此地址我必须通过curl。 我知道该URL重定向到另一个URL(例如http://sdss.co/go/36a7fe71189fec14c85636f33501f6d2/?.. )。 而另一个URL位于第一个URL的标题(位置)中。 如何在某些变量中获取第二个URL?
对第一个URL进行请求,确认发生重定向并读取Location标头。 从PHP cURL在单个请求中检索响应标头和正文? 和检查cURL服务器响应中的标头 :
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_HEADER, 1);
curl_setopt($curlHandle, CURLOPT_NOBODY, 1);
curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
$redirectResponse = curl_exec($curlHandle);
在那里设置的选项的意思是:返回响应头,不返回响应主体, 不自动跟随重定向并在exec调用中返回结果。
现在,您可以在$redirectResponse
中$redirectResponse
不带正文的HTTP响应标头。 现在,您需要验证它是否为重定向:
$statusCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
if ($statusCode == 301 || $statusCode == 302 || $statusCode == 303)
{
$headerLength = curl_getinfo($curlHandle, CURLINFO_HEADER_SIZE);
$responseHeaders = substr($redirectResponse, 0, $headerLength);
$redirectUrl = getLocationHeader($responseHeaders);
}
然后创建一个函数来做到这一点:
function getLocationHeader($responseHeaders)
{
}
在这里,您将要在HTTP换行符( \\r\\n
)上explode()
$responseHeaders
并找到以location
开头的标头。
另外,您可以使用更抽象的HTTP客户端库( 例如Zend_Http_Client
,在其中更容易获得标头。
我做到了,就像CodeCaster所说的那样。 这是我的函数'getLocationHeader': function getLocationHeader($responseHeaders) { if (preg_match('/Location:(.+)Vary/is', $redirectResponse, $loc)) { $location = trim($loc[1]); return $location; } return FALSE; }
function getLocationHeader($responseHeaders) { if (preg_match('/Location:(.+)Vary/is', $redirectResponse, $loc)) { $location = trim($loc[1]); return $location; } return FALSE; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.