2013-12-14 42 views
1

嗨,我知道它在StackOverFlow上的一個非常常見的主題。 我已經花了整整一週的時間來搜索它。獲取curl中最後一個重定向的url php

我有一個網址:abc.com/default.asp?strSearch=19875379

這進一步重定向到該網址:abc.com/default.asp?catid={170D4F36-39F9-4C48-88EB- CFC8DDF1F531} & details_type = 1 &的itemid = {49F6A281-8735-4B74-A170-B6110AF6CC2D}

我已經作出了努力,得到使用捲曲在我的PHP代碼最終URL,但不能做到這一點。

這裏是我的代碼:

<?php 
$name="19875379"; 
$url = "http://www.ikea.co.il/default.asp?strSearch=".$name; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$a = curl_exec($ch); 
curl_close($ch); 
// the returned headers 
$headers = explode("\n",$a); 
// if there is no redirection this will be the final url 
$redir = $url; 
// loop through the headers and check for a Location: str 
$j = count($headers); 
for($i = 0; $i < $j; $i++){ 
// if we find the Location header strip it and fill the redir var  
//print_r($headers); 
if(strpos($headers[$i],"Location:") !== false){ 
     $redir = trim(str_replace("Location:","",$headers[$i])); 
     break; 
    } 
} 
// do whatever you want with the result 
echo $redir; 
?> 

它給我的網址 「abc.com/default.asp?strSearch=19875379」,而不是這個網址「abc.com/default.asp?catid={170D4F36 -39F9-4C48-88EB-CFC8DDF1F531} & details_type = 1 &的itemid = {49F6A281-8735-4B74-A170-B6110AF6CC2D}」

預先感謝你的幫助:)

回答

3

謝謝大家幫我處理我的情況。

其實我想開發一個在以色列(以希伯來語)使用的ikea網站的php中的刮板。 經過了很長時間,我意識到在URL中沒有服務器端重定向,我把它放到重定向的url中。它可能是JavaScript重定向。 我現在已經實現了下面的代碼,它適用於我。再次

<?php 
$name="19875379"; 
$url = "http://www.ikea.co.il/default.asp?strSearch=".$name; 

$ch = curl_init(); 
$timeout = 0; 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
curl_setopt($ch, CURLOPT_HEADER, TRUE); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
$header = curl_exec($ch); 
$redir = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 
//print_r($header); 

$x = preg_match("/<script>location.href=(.|\n)*?<\/script>/", $header, $matches); 
$script = $matches[0]; 
$redirect = str_replace("<script>location.href='", "", $script); 
$redirect = "http://www.ikea.co.il" . str_replace("';</script>", "", $redirect); 

echo $redirect; 
?> 

謝謝大家:)

1

首先,我沒有看到任何重定向,而我已經在您的代碼上運行了。無論如何,這裏有幾件事你可以做到這一點(保持你的方法完好):

首先,確保標題將返回到你的捲曲輸出(在這種情況下$ a)。

curl_setopt($ch, CURLOPT_HEADER, true); 

現在,只從整個http響應中分離標題部分。

// header will be at 0 index, and html will be at 1 index. 
$header = explode("\n\r",$a); 

將標題字符串分解爲標題數組。

$headers = explode("\n", $header[0]);