0

我有一个附属 URL 像http://track.abc.com/?affid=1234 打开这个链接会去http://www.abc.com

现在我想执行http://track.abc.com/?affid=1234Using CURL,现在我如何http://www.abc.com 使用 Curl 获取?

4

2 回答 2

2

If you want cURL to follow redirect headers from the responses it receives, you need to set that option with:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

You may also want to limit the number of redirects it follows using:

curl_setopt($ch, CURLOPT_MAXREDIRS, 3);

So you'd using something similar to this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://track.abc.com/?affid=1234");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);

Edit: Question wasn't exactly clear but from the comment below, if you want to get the redirect location, you need to get the headers from cURL and parse them for the Location header:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://track.abc.com/?affid=1234");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, true);
$data = curl_exec($ch);

This will give you the headers returned by the server in $data, simply parse through them to get the location header and you'll get your result. This question shows you how to do that.

于 2013-01-14T11:39:31.770 回答
-1

我编写了一个函数,该函数将从 cURL 标头响应中提取任何标头。

function getHeader($headerString, $key) {
    preg_match('#\s\b' . $key . '\b:\s.*\s#', $headerString, $header);
    return substr($header[0], strlen($key) + 3, -2);
}

在这种情况下,您正在寻找标头Location的值。我通过使用 cURL从重定向到http://google.se的 TinyURL 检索标头来测试该功能。

$url = "http://tinyurl.com/dtrkv";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);

$location = getHeader($data, 'Location');
var_dump($location);

var_dump 的输出。

string(16) "http://google.se"
于 2013-01-14T12:19:48.660 回答