[英]cURL get url from redirect
我目前正在使用cURL嘗試從網站刮刀的重定向獲取URL。 我只需要網站上的網址。 我在過去幾天研究過stackoverflow和其他網站,但都沒有成功。 我目前使用的代碼來自這個網站:
$url = "http://www.someredirect.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_NOBODY, true);
$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
curl_close($ch);
echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';
任何幫助將不勝感激!
在您的特定情況下,服務器正在檢查某些用戶代理字符串。
當服務器檢查用戶代理字符串時,只有當服務器看到“有效”(根據服務器)用戶代理時,它才會響應302
重定向狀態代碼。 任何“無效”用戶代理都不會收到302
重定向狀態代碼響應或Location:
標頭。
在您的特定情況下,當服務器收到來自“無效”用戶代理的請求時,它會響應200
OK狀態代碼,而響應正文中沒有文本。
( 注意 :在下面的代碼中,提供的實際URL已被示例替換。)
假設http://www.example.com
的服務器檢查用戶代理字符串,並且http://www.example.com/product/123/
重定向到http://www.example.org/abc
。
在PHP中,您的解決方案是:
<?php
$url = 'http://www.example.com/product/123/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64; rv:21.0) Gecko/20100101 Firefox/21.0"); // Necessary. The server checks for a valid User-Agent.
curl_exec($ch);
$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
curl_close($ch);
echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';
並且,此腳本的輸出將是: http://www.example.org/abc
: http://www.example.org/abc
。
嘗試使用此代碼:
function curl_last_url(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
$mr = $maxredirect === null ? 5 : intval($maxredirect);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
if ($mr > 0) {
echo $mr;
echo $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$rch = curl_copy_handle($ch);
curl_setopt($rch, CURLOPT_HEADER, true);
curl_setopt($rch, CURLOPT_NOBODY, true);
curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
do {
curl_setopt($rch, CURLOPT_URL, $newurl);
$header = curl_exec($rch);
if (curl_errno($rch)) {
$code = 0;
} else {
$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
echo $code;
if ($code == 301 || $code == 302) {
preg_match('/Location:(.*?)\n/', $header, $matches);
$newurl = trim(array_pop($matches));
} else {
$code = 0;
}
}
} while ($code && --$mr);
curl_close($rch);
if (!$mr) {
if ($maxredirect === null) {
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
} else {
$maxredirect = 0;
}
return false;
}
curl_setopt($ch, CURLOPT_URL, $newurl);
}
return $newurl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.