当前位置: 移动技术网 > IT编程>开发语言>PHP > php的urlencode()URL编码函数浅析

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

2019年04月21日  | 移动技术网IT编程  | 我要评论
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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网