获取到一个短连接,需要将短连接转换成真实的网址,通过查资料,发现 php 提供了一个函数 get_headers(),可以完成这个任务,先把 头部信息获取到,然后再分析跳转地址即可.
利用get_headers() 函数获取http头,php 自带的get_headers()取得服务器响应一个 http 请求所发送的所有标头, 获取301状态肯定没问题.
例子,代码如下:
$url = 'http://dwz.cn/29uqh7'; $headers = get_headers($url, true); print_r($headers); //输出跳转到的网址 echo $headers['location'];
//附:
array ( [0] => http/1.1 302 moved temporarily [location] => http://www.phprm.com [content-type] => array ( [0] => text/html;charset=utf-8 [1] => text/html;charset=utf-8 ) [server] => array ( [0] => weibo [1] => bws/1.0 ) [content-length] => array ( [0] => 203 [1] => 16424 ) [date] => array ( [0] => thu, 12 dec 2013 10:42:25 gmt [1] => thu, 12 dec 2013 10:42:25 gmt ) [x-varnish] => 2893360335 [age] => 0 [via] => 1.1 varnish [connection] => array ( [0] => close [1] => close ) )
好了我们看一个获取短网址跳转之前的网址,代码如下:
$header = get_headers($url, 1); if (strpos($header[0], '301') || strpos($header[0], '302')) { if (is_array($header['location'])) { return $header['location'][count($header['location'])-1]; } else { return $header['location']; } } else { return $url; }
本文地址:
转载随意,但请附上文章地址:-)