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

Doria ·
更新时间:2024-09-21
· 982 次阅读

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 您可能感兴趣的文章:php中iconv函数使用方法PHP date函数参数详解PHP字符转义相关函数小结(php下的转义字符串)php strstr查找字符串中是否包含某些字符的查找函数PHP下编码转换函数mb_convert_encoding与iconv的使用说明PHP 查找字符串常用函数介绍PHP中的函数-- foreach()的用法详解php数组函数序列之array_unique() - 去除数组中重复的元素值php set_time_limit(0) 设置程序执行时间的函数给大家分享几个常用的PHP函数



url编码 函数 urlencode PHP

需要 登录 后方可回复, 如果你还没有账号请 注册新账号