![]() |
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 (“.”).
<html>
<head>
<title>devtrends.com URL Encode and Decode</title>
<STYLE>
<!--
.outbox {
padding:10px;
margin:4px;
margin-bottom:15px;
border:1px dashed #9E7760;
background-color:#DBCABF;
}
-->
</STYLE>
</head>
<body style="background-color:#FFFFFF;">
<p style="text-align:center;font-family:verdana;font-size:20px;">url encode and decode</p>
<center>
<?php
if ($_POST['dir'] == "e") {
?><div><?php
echo urlencode($_POST['url']);
?></div><?php
} elseif ($_POST['dir'] == "d") {
?><div><?php
echo urldecode($_POST['url']);
?></div><?php
} elseif ($_POST['dir'] == "c") {
?><div><?php
echo myurlencode($_POST['url']);
?></div><?php
}
?>
<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>
</select>
<input type="submit" value="process" />
</form>
</center>
<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>
</body>
</html>
<?php
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;
}
?>
