PHP:使随机字符串URL安全并撤消任何使其安全的内容

Sta*_*bie 4 php urlencode

给定一个随机生成的字符串,如何将其转换为URL安全 - 然后"取消转换"它?

PHP的bin2hex功能(参见:http://www.php.net/manual/en/function.bin2hex.php)似乎可以安全地将字符串转换为URL安全字符.该hex2bin函数(参见:http://www.php.net/manual/en/function.hex2bin.php)可能尚未准备好.以下自定义hex2bin函数有时会起作用:

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;
}
Run Code Online (Sandbox Code Playgroud)

它只适用于函数的输入是有效bin2hex字符串.如果我发送的东西不是由bin2hex它产生的,它就会死掉.我似乎无法在出现错误的情况下抛出异常.

有什么建议我可以做什么?我没有开始使用hex2bin/bin2hex.我需要能够将随机字符串转换为URL安全字符串,然后反转该过程.

Dim*_*mme 9

你想要做的是URL编码/解码字符串:

$randomString = ...;

$urlSafe = urlencode($randomString);

$urlNotSafe = urldecode($urlSafe); // == $randomString
Run Code Online (Sandbox Code Playgroud)