Using PHP urlencode to Encode URLs with Special and Non-ASCII Characters
This article explains the importance of URL encoding for transmitting special and non-ASCII characters, demonstrates how to use PHP’s urlencode (and rawurlencode) function with example code for English and Chinese strings, and discusses practical considerations such as handling spaces in GET requests.
URL encoding is essential for transmitting data on the Internet when URLs contain special characters (such as spaces or ampersands) or non-ASCII characters (such as Chinese or Japanese), ensuring correct transmission and parsing.
The PHP built-in function urlencode converts these characters into a URL-safe format that can be parsed and transmitted.
Example with an English string:
<?php
// String to encode
$str = "Hello World!";
// Encode using urlencode
$encodedStr = urlencode($str);
// Output the encoded string
echo $encodedStr;
?>Running the above code outputs the URL-encoded version of "Hello World!", which is %48%65%6c%6c%6f%20%57%6f%72%6c%64%21 .
When the URL contains non-ASCII characters, the same function can be used. Example with a Chinese string:
<?php
// String to encode
$str = "你好,世界!";
// Encode using urlencode
$encodedStr = urlencode($str);
// Output the encoded string
echo $encodedStr;
?>This produces the encoded string %e4%bd%a0%e5%a5%bd%ef%bc%8c%e4%b8%96%e7%95%8c%ef%bc%81 .
In real applications, URL encoding is commonly used to pass parameters to a server, such as in GET requests, to preserve data integrity and prevent special characters from breaking the URL structure.
Note that urlencode encodes spaces as "+". If you need spaces encoded as "%20", use the rawurlencode function instead.
In summary, using PHP’s urlencode (or rawurlencode ) allows developers to safely encode special and non-ASCII characters in URLs, improving program stability and security.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.