StackOverflowNewbie
StackOverflowNewbie

Reputation: 40633

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

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.

Upvotes: 4

Views: 2154

Answers (2)

Brad
Brad

Reputation: 163262

You can use urlencode()/urldecode().

Upvotes: 1

dimme
dimme

Reputation: 4424

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

$randomString = ...;

$urlSafe = urlencode($randomString);

$urlNotSafe = urldecode($urlSafe); // == $randomString

Upvotes: 9

Related Questions