Open In App

How to Encode and Decode URLs in PHP ?

In PHP, encoding and decoding URLs is a common task when working with web applications, especially when handling user input or constructing URLs dynamically. URL encoding is necessary to ensure that special characters in URLs are properly represented, while URL decoding is used to retrieve the original data from encoded URLs.

Syntax

// Encode a URL
$encodedURL = urlencode("https://geeksforgeeks.org/?q=hello geeks");

// Decode a URL
$decodedURL = urldecode($encodedURL);

echo $encodedURL; // Output: https%3A%2F%geeksforgeeks.org%2F%3Fq%3Dhello+geeks
echo $decodedURL; // Output: https://geeksforgeeks.org/?q=hello geeks

Important Points:

Difference between urlencode() and urldecode()

urlencode() urldecode()
Encodes a string for use in a URL Decodes a URL-encoded string
Replaces special characters with their hexadecimal representation Converts hexadecimal representations back to their original characters

Usage

Article Tags :