欢迎各位兄弟 发布技术文章
这里的技术是共享的
 
  在PHP中有urlencode()、urldecode()、rawurlencode()、rawurldecode()这些函数来解决网页URL编码解码问题。
理解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.phpernote.com/中文.rar -> 浏览器自动转换为 -> http://www.phpernote.com/%D6%D0%CE%C4.rar
注意:Firefox对GB2312的Encode的中文URL支持不好,因为它默认是utf-8编码发送URL的,但是ftp://协议可以,应该算是Firefox一个bug。
编码为utf-8的html文件中:
http://www.phpernote.com/中文.rar -> 浏览器自动转换为 -> http://www.phpernote.com/%E4%B8%AD%E6%96%87.rar
PHP中的urlencode:
| 1 | //GB2312的Encode | 
| 2 | echourlencode("中文-_. ")."\n"; //%D6%D0%CE%C4-_.+ | 
| 3 | echourldecode("%D6%D0%CE%C4-_. ")."\n"; //中文-_. | 
| 4 | echorawurlencode("中文-_. ")."\n"; //%D6%D0%CE%C4-_.%20 | 
| 5 | echorawurldecode("%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函数。
| 1 | $url= 'http://www.phpernote.com/中文.rar'; | 
| 2 | echourlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."\n"; | 
| 3 | echorawurlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."\n"; | 
| 4 | //http%3A%2F%2Fwww.huikaiche.com%2F%E4%B8%AD%E6%96%87.rar | 
应用实例:
| 01 | functionparseurl($url=""){ | 
| 02 |     $url= rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8')); | 
| 03 |     $a= array("%3A", "%2F", "%40"); | 
| 04 |     $b= array(":", "/", "@"); | 
| 05 |     $url= str_replace($a, $b, $url); | 
| 06 |     return$url; | 
| 07 | } | 
| 08 | $url="ftp://yongfu:password@www.huikaiche.com/中文/中文.rar"; | 
| 09 | echoparseurl($url); | 
| 10 | //ftp://yongfu:password@www.huikaiche.com/%D6%D0%CE%C4/%D6%D0%CE%C4.rar | 
来自 http://www.phpernote.com/php-template/200.html
php教程 ENCODE编码,DECODE解码
/**
 * @ string $str 要编码的字符串
 * @ string $ende 操作ENCODE编码,DECODE解码
 * @ string $key hash值
 * @return string
 */
function code($str, $ende, $key = '') {
 $coded = '';
 $keylength = strlen($key);
 $str = $ende == 'DECODE' ? base64_decode($str) : $str;
 for($i = 0; $i < strlen($str); $i += $keylength) {
  $coded .= substr($str, $i, $keylength) ^ $key;
 }
 $coded = $ende == 'ENCODE' ? str_replace('=', '', base64_encode($coded)) : $coded;
 return $coded;
}
我要们要 ENCODE编码,DECODE解码 只要设置$ende的参数就行了。
来自 http://www.111cn.net/phper/21/4ff09be0c2a9a20f271962e35f8cf0e6.htm