如何找到使用cURL重定向到的位置? [英] How can I find where I will be redirected using cURL?
问题描述
我正在尝试使curl遵循重定向,但是我无法完全使其正常工作.我有一个字符串,我想将它作为GET参数发送到服务器并获取结果URL.
I'm trying to make curl follow a redirect but I can't quite get it to work right. I have a string that I want to send as a GET param to a server and get the resulting URL.
示例:
String = Kobold害虫
网址= www.wowhead.com/search?q=Kobold+Worker
String = Kobold Vermin
Url = www.wowhead.com/search?q=Kobold+Worker
如果您转到该URL,它将把您重定向到"www.wowhead.com/npc=257".我希望curl将此URL返回到我的PHP代码,以便我可以提取"npc = 257"并使用它.
If you go to that url it will redirect you to "www.wowhead.com/npc=257". I want curl to return this URL to my PHP code so that i can extract the "npc=257" and use it.
当前代码:
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.wowhead.com/search?q=Kobold+Worker ,而不是 www.wowhead.com/npc=257 .
我怀疑PHP会在外部重定向发生之前返回.我该如何解决?
I suspect PHP is returning before the external redirect happens. How can I fix this?
推荐答案
要使cURL遵循重定向,请使用:
To make cURL follow a redirect, use:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Erm ...我认为您实际上并没有执行卷曲操作...
Erm... I don't think you're actually executing the curl... Try:
curl_exec($ch);
...在设置选项之后,在curl_getinfo()
调用之前.
...after setting the options, and before the curl_getinfo()
call.
如果您只是想找出页面重定向到的位置,我会使用建议此处,只需使用Curl抓取标头并从标头中提取Location:标头:
If you just want to find out where a page redirects to, I'd use the advice here, and just use Curl to grab the headers and extract the Location: header from them:
$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]);
}
这篇关于如何找到使用cURL重定向到的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!