How to Decode URLs in PHP Using urldecode
This article explains how to use PHP's urldecode function to decode URL parameters and full URLs, provides step‑by‑step code examples—including decoding encoded Chinese characters—and demonstrates the complementary use of urlencode for proper encoding and decoding of special characters.
In web development, we often need to handle URL parameters, and sometimes special characters are encoded, so we need to decode them. PHP provides a function "urldecode" for decoding URLs.
In this article, we will learn how to use PHP's urldecode function to decode URLs, with practical code examples.
First, let's look at a simple example. Suppose we have the following URL parameter:
$url = "https://example.com/?name=%E5%BC%A0%E4%B8%89&age=20";In this URL, the "name" parameter value is encoded as "%E5%BC%A0%E4%B8%89". We can use urldecode to decode it:
$name = urldecode($_GET['name']);
echo $name;Running the above code yields "张三". The urldecode function decodes the encoded string into normal Chinese characters.
Besides decoding URL parameters, we can also use urldecode to decode an entire URL. Example:
$url = "https%3A%2F%2Fexample.com%2F%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D20";
$decodedUrl = urldecode($url);
echo $decodedUrl;Executing this code outputs "https://example.com/?name=张三&age=20". The urldecode function converts the whole URL into a readable form.
Note that when a URL contains special characters or their encoding, we should first use urlencode to encode the URL, then urldecode to decode it, ensuring correctness of parameters or the URL itself.
$name = "张三";
$encodedName = urlencode($name);
$decodedName = urldecode($encodedName);
echo $decodedName;Running this code yields "张三", showing that encoding then decoding returns the original Chinese characters.
In summary, using PHP's urldecode to decode URLs is straightforward; whether decoding parameters or the whole URL, a single line of code suffices, making it very useful for URL handling.
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.