如何使用 cURL 找到我将被重定向到的位置? [英] How can I find where I will be redirected using cURL?

查看:20
本文介绍了如何使用 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 Vermin
网址 = 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=Kobold+Worker 而不是 www.wowhead.com/npc=257.

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);

呃...我不认为你真的在执行 curl...尝试:

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屋!

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