Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: make random string URL safe and undo whatever made it safe

Tags:

php

urlencode

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.

like image 216
StackOverflowNewbie Avatar asked Dec 27 '22 10:12

StackOverflowNewbie


1 Answers

What you want to do is URL encode/decode the string:

$randomString = ...;

$urlSafe = urlencode($randomString);

$urlNotSafe = urldecode($urlSafe); // == $randomString
like image 134
Dimme Avatar answered Feb 01 '23 23:02

Dimme