URL Encode and Decode

url encode
URL encoder and decoder to encode strings using the URL encoding standard (%[hex]). This script utilizes both, PHP's built-in urlencode() and urldecode() functions, and a custom function that encodes all characters except letters and numbers. And, of course, I have included the simple script below for those that are curious.

show me!

Being that I am not as skilled in PHP as I am in ASP or ASP.NET, I did not realize that PHP already had functions for URL encoding and decoding, urlencode() and urldecode(), respectively. I started this simple page by creating my own function and naming it, well, urlencode(). After noticing that my text editor (UltraEdit) colored the word, I did a simple Google search and realized that I was wasting my time…or was I? I kept the custom script as it encodes more characters than the standard PHP urlencode() function does, such as the period character (“.”).

 <title>devtrends.com URL Encode and Decode</title>

 .outbox {
 border:1px dashed #9E7760;


<body style="background-color:#FFFFFF;">

<p style="text-align:center;font-family:verdana;font-size:20px;">url encode and decode</p>


 if ($_POST['dir'] == "e") {
 echo urlencode($_POST['url']);
 } elseif ($_POST['dir'] == "d") {
 echo urldecode($_POST['url']);
 } elseif ($_POST['dir'] == "c") {
 echo myurlencode($_POST['url']);


 <form method="post" action="index.php">
 <input type="text" name="url" size="50" value="<?php echo $_POST['url'] ?>" />

 <select name="dir">
 <option value="e"<?php if($_POST['dir'] == "e"){echo "selected";} ?>>Encode (PHP)</option>
 <option value="c"<?php if($_POST['dir'] == "c"){echo "selected";} ?>>Encode (custom)</option>
 <option value="d"<?php if($_POST['dir'] == "d"){echo "selected";} ?>>Decode (PHP)</option>

 <input type="submit" value="process" />

<p style="text-align:center;font-family:verdana;font-size:12px;">note: the custom encode will encode all characters except letters and numbers (ascii 33-47,58-64,91-96,123-126).</p>

<p style="text-align:center;font-family:verdana;font-size:10px;"><a href="http://www.devtrends.com/">a simple service of www.devtrends.com</a></p>



function myurlencode($myurlstr) {
 //replace the % first
 $myurlstr = str_replace(chr(37), "%25", $myurlstr);

 for ($i=33;$i<=36;$i++) {
 $myurlstr = str_replace(chr($i), "%" . dechex($i), $myurlstr);
 for ($i=38;$i<=47;$i++) {
 $myurlstr = str_replace(chr($i), "%" . dechex($i), $myurlstr);
 for ($i=58;$i<=64;$i++) {
 $myurlstr = str_replace(chr($i), "%" . dechex($i), $myurlstr);
 for ($i=91;$i<=96;$i++) {
 $myurlstr = str_replace(chr($i), "%" . dechex($i), $myurlstr);
 for ($i=123;$i<=126;$i++) {
 $myurlstr = str_replace(chr($i), "%" . dechex($i), $myurlstr);

 return $myurlstr;


One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *