我正在尝试让curl遵循一个重定向,但是我不能让它正常工作。我有一个字符串,我想将它作为GET参数发送到服务器,并获得结果URL。
示例:
字符串= Kobold Vermin
Url =www.wowhad.com/search?q=Kobold+Worker
如果您转到该url,它会将您重定向到“www.wowhad.com/npc=257”。我希望curl将这个URL返回给我的PHP代码,这样我就可以提取"npc=257“并使用它。
当前代码:
function npcID($name) {
$urltopost = "http://www.wowhead.com/search?q=" . $name;
$ch = curl_init();
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_URL, $urltopost);
curl_setopt($ch, CURLOPT_REFERER, "http://www.wowhead.com");
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
}
但是,这将返回www.wowhad.com/search?q=Kobold+Worker,而不是www.wowhad.com/npc=257。
我怀疑PHP会在外部重定向发生之前返回。我该如何解决这个问题呢?
发布于 2010-08-19 16:47:39
要使cURL遵循重定向,请使用:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
呃..。我不认为你真的在做卷曲...尝试:
curl_exec($ch);
在curl_getinfo()
调用之前,...after设置选项。
编辑:如果你只是想找出页面重定向到哪里,我会使用建议here,然后使用Curl抓取标题并从中提取Location: header:
$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);
$result = curl_exec($ch);
if (preg_match('~Location: (.*)~i', $result, $match)) {
$location = trim($match[1]);
}
发布于 2015-02-11 23:47:31
将此行添加到curl inizialization
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
并在curl_close之前使用getinfo
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );
es:
$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_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$html = curl_exec($ch);
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );
curl_close($ch);
发布于 2011-03-22 11:19:21
上面的答案在我的一台服务器上不起作用,这与basedir有关,所以我对它进行了一些重新处理。下面的代码可以在我的所有服务器上运行。
$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
if(strpos($headers[$i],"Location:") !== false){
$redir = trim(str_replace("Location:","",$headers[$i]));
break;
}
}
// do whatever you want with the result
echo redir;
https://stackoverflow.com/questions/3519939
复制相似问题