URL Encoding Support in PHP

This section provides a tutorial example on how to perform URL encoding/decoding and application/x-www-form-urlencoded encoding/decoding in PHP.

If you need to do URL coding in PHP language, there are 4 built-in functions you can use:

string rawurlencode(string $str)
   Encodes the given string according to RFC 1738

string rawurldecode(string $str)
   Decodes the given RFC 1738 encoded string

string urlencode(string $str)
   Encodes the given string based on application/x-www-form-urlencoded

string urldecode(string $str)
   Decodes the given application/x-www-form-urlencoded encoded string

Example 1 - URL encoding/decoding PHP script:

<?php
# URL_Encoding_Test.php
# Copyright (c) 2007 HerongYang.com. All Rights Reserved.
#
   $theInput = "和荣, how a u?";
   $theExpected = "%E5%92%8C%E8%8D%A3%2C%20how%20a%20u%3F";
   $theEncoded = rawurlencode($theInput);
   $theDecoded = rawurldecode($theEncoded);
   echo "   Input   : $theInput\n";
   echo "   Encoded : $theEncoded\n";
   echo "   Expected: $theExpected\n";
   echo "   Decoded : $theDecoded\n";
?>

Output:

   Input   : 和荣, how a u?
   Encoded : %E5%92%8C%E8%8D%A3%2C%20how%20a%20u%3F
   Expected: %E5%92%8C%E8%8D%A3%2C%20how%20a%20u%3F
   Decoded : 和荣, how a u?

Example 2 - application/x-www-form-urlencoded encoding/decoding PHP script:

<?php
# x-www-form-urlencoded_Test.php
# Copyright (c) 2007 HerongYang.com. All Rights Reserved.
#
   $theInput = "和荣, how a u?";
   $theExpected = "%E5%92%8C%E8%8D%A3%2C+how+a+u%3F";
   $theEncoded = urlencode($theInput);
   $theDecoded = urldecode($theEncoded);
   echo "   Input   : $theInput\n";
   echo "   Encoded : $theEncoded\n";
   echo "   Expected: $theExpected\n";
   echo "   Decoded : $theDecoded\n";
?>

Output:

   Input   : 和荣, how a u?
   Encoded : %E5%92%8C%E8%8D%A3%2C+how+a+u%3F
   Expected: %E5%92%8C%E8%8D%A3%2C+how+a+u%3F
   Decoded : 和荣, how a u?

Conclusion: PHP supports both URL encoding and application/x-www-form-urlencoded encoding.

Table of Contents

 About This Book

 Base64 Encoding

 Base64 Encoding and Decoding Tools

 Base64URL - URL Safe Base64 Encoding

 Base32 Encoding

URL Encoding, URI Encoding, or Percent Encoding

 What Is URL/URI Encoding?

 URL Encoding Variations

 URL Encoding on HTML Form Data - IE

 URL Encoding on HTML Form Data - Firefox

 application/x-www-form-urlencoded Encoding in Java

 URI String and Components in Java

URL Encoding Support in PHP

 UUEncode Encoding

 References

 Full Version in PDF/EPUB