URL Encoding
URL-encodes string. This algorithm is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
function DecimalToHexadecimal($dec)
{
if ($dec < 1) return "0";
$hex = $dec;
$hexStr = "";
while ($dec > 0)
{
$hex = $dec % 16;
if ($hex < 10)
$hexStr = substr_replace($hexStr, chr($hex + 48), 0, 0);
else
$hexStr = substr_replace($hexStr, chr($hex + 55), 0, 0);
$dec = floor($dec / 16);
}
return $hexStr;
}
function EncodeURL($data, $count) {
$result = "";
for ($i = 0; $i < $count; $i++)
{
$c = $data[$i];
if (('a' <= $c && $c <= 'z') || ('A' <= $c && $c <= 'Z') || ('0' <= $c && $c <= '9'))
{
$result .= $c;
}
else
{
$result .= "%";
$result .= str_pad(DecimalToHexadecimal(ord($c)), 2, "0", STR_PAD_LEFT);
}
}
return $result;
}
Example
$data = "jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^";
$value = EncodeURL($data, strlen($data));
Output
jdfgsdhfsdfsd%206445dsfsd7fg%2F%2A%2F%2Bbfjsdgf%25%24%5E