php urlencode()與urldecode()函數(shù)字符編碼原理詳解
Jun 13, 2016 pm 12:03 PM
其原理就是把中文字符轉(zhuǎn)換為十六進(jìn)制并按某種規(guī)則進(jìn)行字符串組合,實(shí)現(xiàn)字符的編碼與解編碼,保證URL數(shù)據(jù)傳遞過(guò)程中字符的完整性和兼容性,主要討論中文字符的編碼情況。
一,F(xiàn)ireFox瀏覽器編碼中文字符
在Firefox瀏覽器下如果輸入中文字符,將會(huì)自動(dòng)實(shí)現(xiàn)URL編碼,如下
按下Enter鍵前
按下Enter鍵后
二,urlencode()函數(shù)原理
urlencode()函數(shù)用于編碼URL字符串,這里主要討論中文字符的編碼情況,
實(shí)例如下
復(fù)制代碼 代碼如下:
echo urlencode('不要迷戀哥');//輸出:%B2%BB%D2%AA%C3%D4%C1%B5%B8%E7
urlencode()函數(shù)原理就是首先把中文字符轉(zhuǎn)換為十六進(jìn)制,然后在每個(gè)字符前面加一個(gè)標(biāo)識(shí)符%,了解了這個(gè)原理,可以實(shí)現(xiàn)自定義的URL編碼函數(shù),代碼如下
復(fù)制代碼 代碼如下:
$string = "不要迷戀哥";
$length = strlen($string);
echo $string;
$result = array();
//十進(jìn)制
for($i=0;$iif(ord($string[$i])>127){
$result[] = ord($string[$i]).' '.ord($string[++$i]);
}
}
var_dump($result);
//十六進(jìn)制
$strings = array();
foreach($result as $v){
$dec = explode(" ",$v);
$strings[] = "%".dechex($dec[0])." "."%".dechex($dec[1]);
}
var_dump($strings);
上面代碼在[PHP實(shí)現(xiàn)中文字符進(jìn)制轉(zhuǎn)換原理分析]一文中中文字符轉(zhuǎn)十六進(jìn)制原理分析部分有詳細(xì)討論,通過(guò)獲取漢字的各個(gè)字符再轉(zhuǎn)換為十六進(jìn)制,同時(shí)在每個(gè)字符前面加上一個(gè)特殊的標(biāo)識(shí)符%,就實(shí)現(xiàn)了urlencode()函數(shù)的功能,輸出結(jié)果如下
然后對(duì)輸出的結(jié)果與直接使用urlencode()編碼的字符進(jìn)行比較,如上:%B2%BB%D2%AA%C3%D4%C1%B5%B8%E7
通過(guò)上面實(shí)例可知,使用urlencode()函數(shù)編碼中文字符實(shí)質(zhì)上就是把字符轉(zhuǎn)換為十六進(jìn)制再在第個(gè)字符左邊加上一個(gè)特殊的標(biāo)識(shí)符%
三,urldecode()函數(shù)原理
使用urldecode()函數(shù)解碼已編碼的 URL 字符串,實(shí)例如下
echo urldecode('%B2%BB%D2%AA%C3%D4%C1%B5%B8%E7');//輸出:不要迷戀哥
urldecode()函數(shù)與urlencode()函數(shù)原理相反,用于解碼已編碼的 URL 字符串,其原理就是把十六進(jìn)制字符串轉(zhuǎn)換為中文字符,結(jié)合上面實(shí)例,同樣可實(shí)現(xiàn)自定義函數(shù)解碼字符串
復(fù)制代碼 代碼如下:
$string = '%B2%BB%D2%AA%C3%D4%C1%B5%B8%E7';
$length = strlen($string);
$hexs = array();
for($i=0;$iif($string[$i] == '%'){
$hexs[] = $string[++$i].$string[++$i];
}
}
$num = count($hexs);
for($i=0;$iecho chr(hexdec($hexs[$i])).chr(hexdec($hexs[++$i]));
}
上面實(shí)例代碼首先按字符串的規(guī)則取出各個(gè)字符的十六進(jìn)制,然后使用hexdec()函數(shù)把十六進(jìn)制轉(zhuǎn)換為十進(jìn)制,然后再使用chr()函數(shù)把十進(jìn)制轉(zhuǎn)換為字符,實(shí)現(xiàn)十六進(jìn)制轉(zhuǎn)換為字符。輸出結(jié)果如下
四,urldecode()與urlencode()函數(shù)說(shuō)明
urlencode
(PHP 3, PHP 4, PHP 5)
urlencode -- 編碼 URL 字符串
說(shuō)明
string urlencode ( string str )
返回字符串,此字符串中除了 -_. 之外的所有非字母數(shù)字字符都將被替換成百分號(hào)(%)后跟兩位十六進(jìn)制數(shù),空格則編碼為加號(hào)(+)。此編碼與 WWW 表單 POST 數(shù)據(jù)的編碼方式是一樣的,同時(shí)與 application/x-www-form-urlencoded 的媒體類(lèi)型編碼方式一樣。由于歷史原因,此編碼在將空格編碼為加號(hào)(+)方面與 RFC1738 編碼(參見(jiàn) rawurlencode())不同。此函數(shù)便于將字符串編碼并將其用于 URL 的請(qǐng)求部分,同時(shí)它還便于將變量傳遞給下一頁(yè)
urldecode
(PHP 3, PHP 4, PHP 5)
urldecode -- 解碼已編碼的 URL 字符串
說(shuō)明
string urldecode ( string str )
解碼給出的已編碼字符串中的任何 %##。返回解碼后的字符串。
五,參考資源
urlencode()說(shuō)明
urldecode()說(shuō)明

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

Use prepared statements in PHP mainly to prevent SQL injection attacks, improve performance, make the code clearer and easier to debug. 1. It effectively prevents SQL injection through parameterized queries, ensuring that user input is always processed as data rather than SQL logic; 2. Preprocessing statements only need to be compiled once when executed multiple times, significantly improving execution efficiency, especially suitable for batch operations; 3. Parameter binding supports position and named placeholders, separates SQL and data, and enhances code readability and maintenance; 4. Errors can be exposed in advance in the prepare stage, and exceptions can be handled uniformly by setting error mode, which helps to quickly debug.

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach
