http://track.abc.com/?affid=1234のようなアフィリエイト URL を持っています。
このリンクを開くと、http://www.abc.com
http://track.abc.com/?affid=1234
今度はUsing CURLを実行したいのですが、どうすればhttp://www.abc.com
Curl で取得できますか?
http://track.abc.com/?affid=1234のようなアフィリエイト URL を持っています。
このリンクを開くと、http://www.abc.com
http://track.abc.com/?affid=1234
今度はUsing CURLを実行したいのですが、どうすればhttp://www.abc.com
Curl で取得できますか?
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.
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"