How to Encode and Decode URL in PHP

09/05/2021

Contents

In this article, you will learn how to encode and decode URL in PHP.

PHP urlencode() and urldecode() Function

To encode a URL in PHP, you can use the urlencode() function. For example:

<?php
  $url = "https://example.com/mypage.html";
  $encoded_url = urlencode($url);
?>

To decode an encoded URL, you can use the urldecode() function. For example:

<?php
  $decoded_url = urldecode($encoded_url);
?>

The urlencode() function in PHP is used to encode a URL string so that it can be safely passed as a parameter in a URL. It replaces certain characters in the URL string with a percent symbol (%) followed by two hexadecimal digits that represent the character’s ASCII value. For example, spaces are encoded as “%20”.

The urldecode() function is used to reverse the process of URL encoding, i.e., it replaces percent-encoded characters with their original characters.

Here’s an example that demonstrates the encoding and decoding of a URL:

<?php
  $url = "https://example.com/my page.html";

  // encode the URL
  $encoded_url = urlencode($url);
  echo $encoded_url . "\n";

  // decode the encoded URL
  $decoded_url = urldecode($encoded_url);
  echo $decoded_url . "\n";
?>

This would produce the following output:

https%3A%2F%2Fexample.com%2Fmy%20page.html
https://example.com/my page.html

As you can see, the original URL has been encoded and then decoded successfully.