Home >Backend Development >PHP Tutorial >关于js和php对url编码的处理方法_PHP

关于js和php对url编码的处理方法_PHP

WBOY
WBOYOriginal
2016-06-01 11:55:161070browse

解决办法: 采用js对URL中的汉字进行escape编码。

复制代码 代码如下:


这样点击链接后的效时:

引用:http://127.0.0.1/shop/product_list.php?p_sort=PHP%u5F00%u53D1%u8D44%u6E90%u7F51

生成了这样的效果, 很明显用PHP的urldecode()或者base64_decode()是无法反解的。

解决方法, 用PHP写一个反解函数:

复制代码 代码如下:
function js_unescape($str){
        $ret = '';
        $len = strlen($str);
        for ($i = 0; $i                 if ($str[$i] == '%' && $str[$i+1] == 'u'){
                        $val = hexdec(substr($str, $i+2, 4));
                      if ($val                       else if($val >6)).chr(0x80|($val&0x3f));
                        else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
                        $i += 5;
                }

                else if ($str[$i] == '%'){
                        $ret .= urldecode(substr($str, $i, 3));
                        $i += 2;
                }
                else $ret .= $str[$i];
        }
       return $ret;
}

注意JS编码会自动转换成为UTF-8, 所以必须进行编码转换才能得到正确的结果,否则会中文乱码。

复制代码 代码如下:
print iconv('utf-8', 'gb2312', js_unescape($_REQUEST['p_sort']));

到此我们就成功地反解了js的escape编码了。

另外我找到个用PHP实现js的escape编码的函数:
复制代码 代码如下:
function phpescape($str){
$sublen=strlen($str);
$retrunString="";
for ($i=0;$iif(ord($str[$i])>=127){
$tmpString=bin2hex(iconv("gb2312","ucs-2",substr($str,$i,2)));
        //$tmpString=substr($tmpString,2,2).substr($tmpString,0,2);window下可能要打开此项
$retrunString.="%u".$tmpString;
$i++;
} else {
        $retrunString.="%".dechex(ord($str[$i]));
}}
return $retrunString;
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn