短网址还原代码的一处优化

之前做过一个oy.gd的短网址网站,同时提供网址缩短和短网址还原的服务,今天去看了下,随意打了一个网址进去(无法访问的错误网址),居然弹了个错误出来,刚才分析了一下,找到了原因并很快解决了,下面分享下过程。

通常短网址还原的方式,都是通过php的get_headers的方法来获取的,网上很多人分享的代码如下:

1
2
3
4
5
6
7
8
9
10
11
function get_real_url($url)
{
$headers = @get_headers($url);
$pattern = '/Location\s*:\s*(https?:[^;\s\n\r]+)/i';
if($locations = preg_grep($pattern,$headers))
{
preg_match($pattern,end($locations),$redirect);
return $redirect[1];
}
return $url;
}

问题正是处在了第三行,preg_grep这个函数的使用上。

查询php手册可知,preg_grep的第二个参数必须是array类型,但是get_headers这个函数的返回值的描述是这样的:

Returns an indexed or associative array with the headers, or FALSE on failure.

也就是说,如果用户输入一个错误无法访问的网址,那么$headers是一个false的boolen,这个方法没有判断$headers的类型便直接使用了preg_grep,那用户输入一个错误或者不存在的网址,自然就会报错了。

查到了原因,那解决方法就非常简单了,下面是我优化后的代码,可以直接拿去使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function get_real_url($url)
{
$headers = @get_headers($url);
$pattern = '/Location\s*:\s*(https?:[^;\s\n\r]+)/i';
if($headers){
if($locations = preg_grep($pattern, $headers))
{
preg_match($pattern, end($locations),$redirect);
return $redirect[1];
}
return $url;
}
else {
$errmsg = "短网址有误,请检查后重新输入!";
return $errmsg;
}
}

加入了对$header变量的判断,当$header为False时,就直接输出错误信息,这样就不会报错了。