Data Encoding Tutorials - Herong's Tutorial Examples - v5.23, by Herong Yang
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
Base64 Encoding and Decoding Tools
Base64URL - URL Safe Base64 Encoding
►URL Encoding, URI Encoding, or Percent Encoding
URL Encoding on HTML Form Data - IE
URL Encoding on HTML Form Data - Firefox
application/x-www-form-urlencoded Encoding in Java