Given a randomly generated string, how do I convert it to make it URL safe -- and then "un convert" it?
PHP's bin2hex
function (see: http://www.php.net/manual/en/function.bin2hex.php) seems to safely convert strings into URL safe characters. The hex2bin
function (see: http://www.php.net/manual/en/function.hex2bin.php) is probably not ready yet. The following custom hex2bin
function works sometimes:
function hex2bin($hexadecimal_data)
{
$binary_representation = '';
for ($i = 0; $i < strlen($hexadecimal_data); $i += 2)
{
$binary_representation .= chr(hexdec($hexadecimal_data{$i} . $hexadecimal_data{($i + 1)}));
}
return $binary_representation;
}
It only works right if the input to the function is a valid bin2hex
string. If I send it something that was not a result of bin2hex
, it dies. I can't seem to get it to throw an exception in case something is wrong.
Any suggestions what I can do? I'm not set on using hex2bin/bin2hex. All I need to to be able to convert a random string into a URL safe string, then reverse the process.
What you want to do is URL encode/decode the string:
$randomString = ...;
$urlSafe = urlencode($randomString);
$urlNotSafe = urldecode($urlSafe); // == $randomString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With