在PHP中有urlencode()、urldecode()、rawurlencode()、rawurldecode()這些函數來解決網頁URL編碼解碼問題。
摘錄一篇關於PHP urlencode()函數的文章,對PHP處理URL作全面瞭解,文章來自373ren排行13,感謝。
理解urlencode:
urlencode:是指針對網頁url中的中文字符的一種編碼轉化方式,最常見的就是Baidu、Google等搜索引擎中輸入中文查詢時候,生成經過 Encode過的網頁URL。urlencode的方式一般有兩種一種是傳統的基於GB2312的Encode(Baidu、Yisou等使用),一種是基於utf-8的Encode(Google,Yahoo等使用)。本工具分別實現兩種方式的Encode與Decode。
中文 -> GB2312的Encode -> ????
中文 -> utf-8的Encode -> 中文
Html中的urlencode:
編碼爲GB2312的html文件中:
http://www.huikaiche.com/中文.rar -> 瀏覽器自動轉換爲 -> http://www.huikaiche.com/????.rar
注意:Firefox對GB2312的Encode的中文URL支持不好,因爲它默認是utf-8編碼發送URL的,但是ftp://協議可以,應該算是Firefox一個bug。
編碼爲utf-8的html文件中:
http://www.fufuok.com/中文.rar -> 瀏覽器自動轉換爲 -> http://www.fufuok.com/中文.rar
PHP中的urlencode:
<?php
//GB2312的Encode
echo urlencode("中文-_. ")."\n"; //????-_.+
echo urldecode("????-_. ")."\n"; //中文-_.
echo rawurlencode("中文-_. ")."\n"; //????-_.
echo rawurldecode("????-_. ")."\n"; //中文-_.
?>
除了 -_. 之外的所有非字母數字字符都將被替換成百分號(%)後跟兩位十六進制數。
urlencode和rawurlencode的區別:
urlencode 將空格則編碼爲加號(+)
rawurlencode 將空格則編碼爲加號( )
代碼都是採用urlencode,從來沒有發現過這個問題,結果導致今天出了嚴重的bug,所有帶空格的url都無法解析了,導致分割好的文件無法下載。使用rawurlencode()函數,解決了這個問題。
如果要使用utf-8的Encode,有兩種方法:
一、將文件存爲utf-8文件,直接使用urlencode、rawurlencode即可。
二、使用mb_convert_encoding函數。
<?php
$url = 'http://www.huikaiche.com/中文.rar';
echo urlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."\n";
echo rawurlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."\n";
//http://www.huikaiche.com/中文.rar
?>
應用實例:
function parseurl($url="")
{
$url = rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8'));
$a = array(":", "/", "@");
$b = array(":", "/", "@");
$url = str_replace($a, $b, $url);
return $url;
}
$url="ftp://yongfu:[email protected]/中文/中文.rar";
echo parseurl($url);
//ftp://yongfu:[email protected]/????/????.rar
?>