php获得网址跳转之后的网址
我们在获取其他网站的图片或视频地址的时候,有时会遇到对方的网站地址为了安全或是防盗链,而做了跳转。我们看一下下面的例子:
访问此网址:
http://mas.prd.am-img.com/2012/08/13/A4SELFAA0011144/3.jpg
直接跳转到:
http://ta.img.cn.amgbs.com/mas/2012/08/13/A4SELFAA0011144/3.jpg
这个时候我们要怎么解决这个问题呢?利用get_headers函数,读取:Location值。废话就不多了,看以下代码:
我们先看一下get_headers函数能获取那些信息。
<?php $url = "http://mas.prd.am-img.com/2012/08/13/A4SELFAA0011144/3.jpg"; print_r(get_headers($url)); ?>
显示的效果为:
Array ( [0] => HTTP/1.1 302 Moved Temporarily [1] => Server: nginx/1.0.10 [2] => Date: Thu, 30 Aug 2012 17:59:50 GMT [3] => Content-Type: text/html [4] => Content-Length: 161 [5] => Connection: close [6] => Location: http://ta.img.cn.amgbs.com/mas/2012/08/13/A4SELFAA0011144/3.jpg [7] => HTTP/1.1 200 OK [8] => Date: Thu, 30 Aug 2012 17:59:50 GMT [9] => Server: PWS/8.0.9.3 [10] => X-Px: ht h0-s1003.p0-foc.cdngp.net [11] => Cache-Control: max-age=300 [12] => Expires: Thu, 30 Aug 2012 18:02:47 GMT [13] => Age: 123 [14] => Content-Length: 217344 [15] => Content-Type: image/jpeg [16] => Last-Modified: Mon, 13 Aug 2012 08:49:02 GMT [17] => Connection: close )
最终代码:
<?php function isfile($url) { $isfile = get_headers($url); $result = str_replace("Location: ","",$isfile[6]); return $result; } $url = "http://mas.prd.am-img.com/2012/08/13/A4SELFAA0011144/3.jpg"; echo isfile($url); ?>