2016-12-03 57 views
1

我需要將廣告網址($ siteURL)重定向到此網址通常在瀏覽器中重定向的最終目的地。假設它在example.com上的重定向,我需要example.com作爲輸出。將此封面網址解析爲php的最終目標網址

$siteURL="http://clkuk.tradedoubler.com/click...."; 

    $ch = curl_init($siteURL); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_Setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    $response = curl_exec($ch); 

    $info = curl_getinfo($ch); 
    //print_r($info); 
    echo $info['url']; 

電流輸出:$ SITEURL值(無重定向)

預期輸出:如果在example.com重定向我需要example.com作爲輸出。

回答

1

在你的情況,重定向沒有完成服務器端與Location:頭(其中cURL將遵循),但眉毛內呃通過一個<meta> HTML標記。

$siteURL的身體包含以下內容:

... 
<meta http-equiv="refresh" content="0;url=https://www.example.com/?..."> 
... 

cURL不遵循HTML/JavaScript重定向,只有瀏覽器做,所以你需要真正分析$siteURL的身體和手動提取的鏈接。

test.php的編輯:處理HTTP報頭和HTML/JS重定向)

<?php 

$urls = array (
    "http://some.domain.test/AFClick.asp?...", 
    "http://another.domain.example/click?..." 
); 

foreach ($urls as $siteURL) { 
    $ch = curl_init($siteURL); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $response = curl_exec($ch); 
    $info = curl_getinfo($ch); 

    print("\nOriginal URL: ${siteURL}\n"); 
    if (empty($info['redirect_url'])) { 
     preg_match('/<meta http-equiv="refresh".*url=(http.*)">/', $response, $matches); 
     print("Redirects to: ${matches[1]}\n"); 
    } else { 
     print("Redirects to: ${info['redirect_url']}\n"); 
    } 

    curl_close($ch); 
} 

?> 

輸出:

Original URL: http://some.domain.test/AFClick.asp?... 
Redirects to: https://target.example.net/?... 

Original URL: http://another.domain.example/click?... 
Redirects to: http://target.example.org/?... 
+0

它去汽車moter網址我想同樣,但我無法使得reg exp獲取元刷新:D –

+0

但它不工作$ siteURL =「http: //clkuk.tradedoubler.com/click?p(245446)a(1291517)g(21669022)epi(3iw19bbmtrmv5o4eeu21s4et2ma7wtn7)「 :( –

+0

這是因爲第二個鏈接使用頭重定向服務器端。我編輯了代碼處理這兩種情況。 – alindt

0

PHP的parse_url你建議立即進行刪除得到你所需要的,看看他們的doxumentation:http://php.net/manual/en/function.parse-url.php

var_dump(parse_url($url,PHP_URL_QUERY)); 

編輯: 對不起..你需要使用parse_str代替parse_url,看下面的例子:

$siteURL="http://scripts.affiliatefuture.com/AFClick.asp?affiliateID=125272&merchantID=6441&programmeID=17908&mediaID=0&tracking=74299X1524119Xa4d1bde1feb3809c50f9f4d03e2f1096&url=https%3A%2F%2Fwww.poshbingo.co.uk%2F"; 

parse_str($siteURL, $output); 
var_dump($output['url']); 
+0

這只是解析URL分成幾部分(3){ [「host」] => string(15)「www.example.com」 [ 「路徑」] => 串(5) 「/路徑」 [ 「查詢」] => 串(17) 「googleguy = Google式」 } 我需要的最終目的地的URL,其中該$ SITEURL降落 –

+0

它不適用於$ siteURL =「http://clkuk.tradedoubler.com/click?p(245446)a(1291517)g(21669022)epi(3iw19bbmtrmv5o4eeu21s4et2ma7wtn7)%22」; 當我們在瀏覽器中正常打開,但你的代碼顯示錯誤 –