在php中有urlencode()、urldecode()、rawurlencode()、rawurldecode()这些函数来解决网页url编码解码问题。
php中urlencode介绍:urlencode是指针对网页url中的中文字符的一种编码转化方式,最常见的就是baidu、google等搜索引擎中输入中文查询时候,生成经过 encode过的网页url。urlencode的方式一般有两种一种是传统的基于gb2312的encode(baidu、yisou等使用),一种是基于utf-8的encode(google,yahoo等使用)。本文分别分析两种方式的encode与decode。
中文 -> gb2312的encode -> %d6%d0%ce%c4
中文 -> utf-8的encode -> %e4%b8%ad%e6%96%87
html中的urlencode:
编码为gb2312的html文件中:
http://www.scutephp.com/中文.rar -> 浏览器自动转换为 -> http://www.scutephp.com/%d6%d0%ce%c4.rar
注意:firefox对gb2312的encode的中文url支持不好,因为它默认是utf-8编码发送url的,但是ftp://协议可以,应该算是firefox一个bug。
编码为utf-8的html文件中:
http://www.scutephp.com/中文.rar -> 浏览器自动转换为 -> http://www.scutephp.com/%e4%b8%ad%e6%96%87.rar
urlencode和rawurlencode的例子:代码
//gb2312的encode
echo urlencode(中文-_. ).\n;
//%d6%d0%ce%c4-_.+
echo urldecode(%d6%d0%ce%c4-_. ).\n;
//中文-_.
echo rawurlencode(中文-_. ).\n;
//%d6%d0%ce%c4-_.%
05echo rawurldecode(%d6%d0%ce%c4-_. ).\n;
//中文-_.
除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数。
urlencode和rawurlencode的区别:urlencode 将空格则编码为加号(+)
rawurlencode 将空格则编码为加号(%20)
我上个版本的txt文件分割器(在线)代码都是采用urlencode,从来没有发现过这个问题,结果导致今天出了严重的bug,所有带空格的url都无法解析了,导致分割好的文件无法下载。使用rawurlencode()函数,解决了这个问题。
如果要使用utf-8的encode,有两种方法:一、将文件存为utf-8文件,直接使用urlencode、rawurlencode即可。
二、使用mb_convert_encoding函数。
代码
$url = 'http://www.phpernote.com/中文.rar';
echo urlencode(mb_convert_encoding($url, 'utf-8', 'gb2312')).\n;
echo rawurlencode(mb_convert_encoding($url, 'utf-8', 'gb2312')).\n;
//http%3a%2f%2fwww.huikaiche.com%2f%e4%b8%ad%e6%96%87.rar
应用实例:
代码
function parseurl($url=){
$url = rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8'));
$a = array(%3a, %2f, %40);
$b = array(:, /, @);
$url = str_replace($a, $b, $url);
return $url;
}
$url=ftp://yongfu:password@www.huikaiche.com/中文/中文.rar;
echo parseurl($url);
//ftp://yongfu:password@www.huikaiche.com/%d6%d0%ce%c4/%d6%d0%ce%c4.rar
