Open In App

How to Encode and Decode a URL in PHP?

Encoding and decoding URLs in PHP are essential tasks when working with web applications, especially for handling user input and constructing query strings. URL encoding ensures that special characters are properly represented in URLs, preventing errors or unexpected behavior during data transmission. PHP provides built-in functions to encode and decode URLs efficiently, allowing developers to manipulate URL components securely.

Approach:

Syntax:

// Encoding a URL
$encodedURL = urlencode($url);
// Decoding a URL
$decodedURL = urldecode($encodedURL);

Example: Implementation to encode/decode the URL.




<?php
 
// URL to encode
 
// Encoding the URL
$encodedURL = urlencode($url);
echo "Encoded URL: $encodedURL\n";
 
// Decoding the URL
$decodedURL = urldecode($encodedURL);
echo "Decoded URL: $decodedURL\n";
 
?>

Output
Encoded URL: https%3A%2F%2Fwww.geeksforgeeks.org%2Fpage.php%3Fquery%3Dhello+geeks
Decoded URL: https://www.geeksforgeeks.org/page.php?query=hello geeks




Features:

Difference between urlencode() and urldecode()

urlencode() Function urldecode() Function
Encodes a string by replacing special characters with their hexadecimal representation preceded by a percent sign (%) Decodes a URL-encoded string, converting hexadecimal representations of special characters back to their original characters
Used to encode URL components, such as query string parameters Employed to decode URL-encoded strings received from external sources
Prevents errors or unexpected behavior in URLs due to special characters or non-ASCII characters Ensures accurate interpretation of URL-encoded strings, allowing applications to process URL components correctly
Article Tags :