php的urlencode()URL编码函数浅析

2015-01-24信息快讯网

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://s.jb51.net/中文.rar -> 浏览器自动转换为 -> http://s.jb51.net/%D6%D0%CE%C4.rar

注意:Firefox对GB2312的Encode的中文URL支持不好,因为它默认是UTF-8编码发送URL的,但是ftp://协议可以,我试过了,我认为这应该算是Firefox一个bug。

编码为UTF-8的html文件中:http://s.jb51.net/中文.rar -> 浏览器自动转换为 -> http://s.jb51.net/%E4%B8%AD%E6%96%87.rar

PHP中的URLEncode:
 
<?php 
//GB2312的Encode 
echo urlencode("中文-_. ")."\n"; //%D6%D0%CE%C4-_.+ 
echo urldecode("%D6%D0%CE%C4-_. ")."\n"; //中文-_. 
echo rawurlencode("中文-_. ")."\n"; //%D6%D0%CE%C4-_.%20 
echo rawurldecode("%D6%D0%CE%C4-_. ")."\n"; //中文-_. 
?> 


除了“-_.”之外的所有非字母数字字符都将被替换成百分号“%”后跟两位十六进制数。

urlencode和rawurlencode的区别:urlencode将空格编码为加号“+”,rawurlencode将空格编码为加号“%20”。

如果要使用UTF-8的Encode,有两种方法:

一、将文件存为UTF-8文件,直接使用urlencode、rawurlencode即可。

二、使用mb_convert_encoding函数:
 
<?php 
$url = 'http://s.jb51.net/中文.rar'; 
echo urlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."\n"; 
echo rawurlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."\n"; 
//http%3A%2F%2Fs.jb51.net%2F%E4%B8%AD%E6%96%87.rar 
?> 


实例:
 
<?php 
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://ud03:password@s.jb51.net/中文/中文.rar"; 
echo parseurl($url); 
//ftp://ud03:password@s.jb51.net/%D6%D0%CE%C4/%D6%D0%CE%C4.rar 
?> 


JavaScript中的URLEncode:

如:%E4%B8%AD%E6%96%87-_.%20%E4%B8%AD%E6%96%87-_.%20

encodeURI不对下列字符进行编码:“:”、“/”、“;”、“?”、“@”等特殊字符。

如:http://s.jb51.net/%E4%B8%AD%E6%96%87.rarhttp%3A%2F%2Fs.jb51.net%2F%E4%B8%AD%E6%96%87.rar
关于Iframe如何跨域访问Cookie和Session的解决方法
php简单开启gzip压缩方法(zlib.output_compression)
PHP中使用cURL实现Get和Post请求的方法
file_get_contents获取不到网页内容的解决方法
利用PHP扩展vld查看PHP opcode操作步骤
CI框架源码阅读,系统常量文件constants.php的配置
PHP下使用CURL方式POST数据至API接口的代码
PHP5.4中json_encode中文转码的变化小结
PHP中CURL方法curl_setopt()函数的参数分享
PHP基础教程(php入门基础教程)一些code代码
PHP gbk环境下json_dencode传送来的汉字
php curl 伪造IP来源的实例代码
解析百度搜索结果link?url=参数分析 (全)
apache+codeigniter 通过.htcaccess做动态二级域名解析
php数据结构 算法(PHP描述) 简单选择排序 simple selection sort
php简单的会话类代码
让Nginx支持ThinkPHP的URL重写和PATHINFO的方法分享
PHP获取url的函数代码
PHP源代码数组统计count分析
linux下为php添加curl扩展的方法
php URL验证正则表达式
PHP通过iconv将字符串从GBK转换为UTF8字符集
PHP setcookie设置Cookie用法(及设置无效的问题)
php header Content-Type类型小结
php中关于codeigniter的xmlrpc的类在进行数据交换时的类型问题
php URL跳转代码 减少外链
php自动获取字符串编码函数mb_detect_encoding
php异常:Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE eval()'d code error
一些PHP Coding Tips(php小技巧)[2011/04/02最后更新]
php array_unique之后json_encode需要注意
©2014-2024 dbsqp.com