簡體   English   中英

PHP獲取重定向URL

[英]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);

結果是:

cURLCURLOPT_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM