PHP--------解決網址URL編碼問題

在PHP中有urlencode()、urldecode()、rawurlencode()、rawurldecode()這些函數來解決網頁URL編碼解碼問題。php

理解urlencode:html

urlencode: 是指針對網頁url中的中文字符的一種編碼轉化方式,最多見的就是Baidu、Google等搜索引擎中輸入中文查詢時候,生成通過 Encode過的網頁URL。java

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:ui

編碼爲GB2312的html文件中:
http://www.php.com/中文.rar -> 瀏覽器自動轉換爲 -> http://www.php.com/%D6%D0%CE%C4.rar
注意:Firefox對GB2312的Encode的中文URL支持很差,由於它默認是utf-8編碼發送URL的,可是ftp://協議能夠,應該算是Firefox一個bug。搜索引擎

編碼爲utf-8的html文件中:
http://www.php.com/中文.rar -> 瀏覽器自動轉換爲 -> http://www.php.com/%E4%B8%AD%E6%96%87.rar編碼

PHP中的urlencode:url

//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)

我上個版本的txt文件分割器(在線)代碼都是採用urlencode,歷來沒有發現過這個問題,結果致使今天出了嚴重的bug,全部帶空格的url都沒法解析了,致使分割好的文件沒法下載。使用rawurlencode()函數,解決了這個問題。

若是要使用utf-8的Encode,有兩種方法:

1、將文件存爲utf-8文件,直接使用urlencode、rawurlencode便可。
2、使用mb_convert_encoding函數。

$url = 'http://www.php.com/中文.rar';
echo urlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."\n";
echo rawurlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."\n";
//http%3A%2F%2Fwww.huikaiche.com%2F%E4%B8%AD%E6%96%87.rar

應用實例:

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://yongfu:password@www.huikaiche.com/中文/中文.rar";
echo parseurl($url);
//ftp://yongfu:password@www.huikaiche.com/%D6%D0%CE%C4/%D6%D0%CE%C4.rar
相關文章
相關標籤/搜索