使curl跟随重定向? [英] Make curl follow redirects?

查看:216
本文介绍了使curl跟随重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让curl跟随重定向,但我不能让它工作正常。我有一个字符串,我想作为一个GET param发送到服务器,并得到结果的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 Vermin

Url = www.wowhead.com/search?q=Kobold+Worker

如果您访问该网址,将会将您重定向到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=

This however returns www.wowhead.com/search?q=Kobold+Worker and not 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 ...我不认为你实际上正在执行卷曲... Try:

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抓取标题并提取位置:来自他们的标题:

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);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
 $l = trim($r[1]);

这篇关于使curl跟随重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆