Using PHP urlencode() and urldecode() Functions for URL Encoding and Decoding
This article explains PHP's urlencode() and urldecode() functions, shows their syntax and practical code examples, compares them with rawurlencode() and rawurldecode(), and discusses when to use each for proper handling of special characters in URLs.
In PHP, URL encoding and decoding are common operations that convert special characters in a URL to their encoded values and back.
PHP offers a set of functions for this purpose; the most frequently used are urlencode() and urldecode() , which are demonstrated with code examples below.
1. urlencode() function
The urlencode() function encodes a string for use in a URL. Its syntax is:
string urlencode(string $str)Example:
$url = "https://www.example.com/index.php?id=123&name=John Doé";
$encoded_url = urlencode($url);
echo $encoded_url;
// Output: https%3A%2F%2Fwww.example.com%2Findex.php%3Fid%3D123%26name%3DJohn+Do%C3%A9The example shows a URL containing spaces and non‑ASCII characters being correctly encoded.
2. urldecode() function
The urldecode() function decodes an encoded URL back to its original form. Its syntax is:
string urldecode(string $str)Example:
$encoded_url = "https%3A%2F%2Fwww.example.com%2Findex.php%3Fid%3D123%26name%3DJohn+Do%C3%A9";
$decoded_url = urldecode($encoded_url);
echo $decoded_url;
// Output: https://www.example.com/index.php?id=123&name=John DoéThis demonstrates that the encoded characters are restored to their original representation.
Besides urlencode() and urldecode() , PHP also provides rawurlencode() and rawurldecode() , which behave similarly but differ slightly in how they treat certain characters.
Using these functions ensures that special characters in URLs are handled correctly, preventing broken links or query‑parameter errors in real‑world applications.
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.