PHP cURL重定向到另一个URL

时间:2017-09-16 03:19:58

标签: php redirect curl

在我的代码中,当我尝试使用cURL获取重定向时,它不会显示新位置,但是当我在浏览器中放入相同的网址时,它会重定向到我不知道的其他地方如何没有重定向规则。但我需要在结果中获得相同的URL。

以下是示例网址

http://www.dailymotion.com/cdn/H264-1280x720/video/x1r819x.mp4?auth=1505704620-2562-a9qmrjvz-6e0f4066eb3a57ce79c011f5c3f932f3

以下是重定向网址

https://proxy-23.sg1.dailymotion.com/video/907/091/106190709_mp4_h264_aac_hd.mp4?auth=1505539349-6658-b3dukan0-a41773a8fa2338e758ce74cff24b0390#cell=sg1&hls_heuristic=1&hls_startFragPrefetch=1

这是我的PHP代码

$url = "http://www.dailymotion.com/cdn/H264-1280x720/video/x1r819x.mp4?auth=1505704620-2562-a9qmrjvz-6e0f4066eb3a57ce79c011f5c3f932f3";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true); // HTTP request is 'HEAD'
$headers=curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $headers, $matches);
curl_close($ch);
$print_newurl =  !empty($matches[1]) ? trim($matches[1][0]) : 'http://www.google.com.fr';
echo $print_newurl;

1 个答案:

答案 0 :(得分:1)

尝试使用CURLOPT_FOLLOWLOCATION跟进重定向。

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

修改

$last_url = curl_getinfo($ch, CURLINFO_REDIRECT_URL);

如果这不起作用,请尝试使用CURLINFO_EFFECTIVE_URL。查看更多http://php.net/manual/en/function.curl-getinfo.php