Using PHP's urlencode Function for URL Encoding
This article explains how PHP's urlencode function encodes special and non‑ASCII characters in URLs, provides example code for English and Chinese strings, discusses practical usage in GET requests, and notes the difference between urlencode and rawurlencode for space handling.
URL encoding is essential for transmitting data on the Internet; when a URL contains special characters or non‑ASCII characters, it must be encoded to ensure correct transmission and parsing.
In PHP, the built‑in urlencode function converts special and non‑ASCII characters into a URL‑safe format. The following example demonstrates its usage:
Running the script outputs the URL‑encoded version of “Hello World!”: %48%65%6c%6c%6f%20%57%6f%72%6c%64%21 .
The function also works with non‑ASCII characters such as Chinese. Example:
Executing this code yields 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, especially 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 rawurlencode instead.
In summary, using PHP’s urlencode function allows easy encoding of 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.