[英]PHP get redirect URL
我已经阅读了关于同一问题的其他一些问题,并在那里尝试了curl示例。 但是,这些示例不适用于该特定网址http://www.prisjakt.no/redirect.php?prisid=182556713
。 我得到的只是带有重定向的相同链接。
您是否有解决方案来获取以下链接的网址,在本例中为http://www.siba.no/tv-lyd-bilde/hodetelefoner/lukkede-hodetelefoner/sennheiser-momentum-109434
?
使用Guzzle的解决方案也可以。
谢谢!
编辑:问题似乎是通过JS而不是带有标头进行的重定向。
Guzzle确实为请求中的重定向提供了一些配置设置
您可以通过将事件侦听器添加到BeforeEvent来“捕获”重定向,如下所示:
$request = $client->createRequest('GET', $url);
$request->getEmitter()->on('before', function (BeforeEvent $event) {
// do something with the event.
});
$response = $client->send($request);
然后,在侦听器中,您可以通过调用以下命令获取新请求的网址:
$event->getRequest()->getUrl()
例如:
$client = new GuzzleHttp\Client();
$request = $client->createRequest('GET', 'http://www.google.com');
$request->getEmitter()->on('before', function (GuzzleHttp\Event\BeforeEvent $e) {
echo $e->getRequest()->getUrl() . PHP_EOL;
});
$response = $client->send($request);
结果是:
将cURL的CURLOPT_FOLLOWLOCATION
选项设置为true
以遵循重定向:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
对于Guzzle,根据他们的文档 ,
默认情况下,Guzzle将使用大多数Web浏览器使用的非RFC兼容实现自动跟踪重定向 。 这意味着POST请求的重定向之后是GET请求。 您可以通过在请求的参数对象上启用严格模式来强制符合RFC:
// Set per request $request = $client->post(); $request->getParams()->set('redirect.strict', true); // You can set globally on a client so all requests use strict redirects $client->getConfig()->set('request.params', array( 'redirect.strict' => true ));
默认情况下,在抛出
Guzzle\\Http\\Exception\\TooManyRedirectsException
之前,Guzzle最多重定向5次。 您可以使用请求对象的redirect.max参数来提高或降低此值:$request->getParams()->set('redirect.max', 2);
function get_real_url($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$html = curl_exec($ch);
$url = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );
curl_close($ch);
return $url;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.