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.

php Courses
php Courses
php Courses
Using PHP urlencode() and urldecode() Functions for URL Encoding and Decoding

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%A9

The 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backend-developmenturlencodeurldecodeurl-encoding
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.