Using PHP urlencode() and urldecode() Functions for URL Encoding and Decoding
This article explains how PHP's urlencode() and urldecode() functions work, provides their syntax and practical code examples, and briefly mentions related rawurlencode() and rawurldecode() functions for handling special characters in URLs during web development.
In PHP, URL encoding and decoding are common operations that convert special characters in a URL to their percent‑encoded forms and back again.
PHP offers a set of functions for these tasks; this article focuses on the frequently used urlencode() and urldecode() functions and provides code examples.
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 a URL‑encoded string 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éThe example demonstrates how the encoded URL is restored to its original characters.
Besides urlencode() and urldecode() , PHP also provides rawurlencode() and rawurldecode() , which behave similarly but handle certain characters slightly differently.
Using these functions ensures that special characters in URLs are processed correctly, preventing broken links or query‑parameter errors and improving security and accuracy in web applications.
In summary, PHP's urlencode() and urldecode() functions offer a straightforward way to perform URL encoding and decoding, and developers can choose the appropriate function based on their specific needs.
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.