2011-11-20 42 views
3

给定一个随机生成的字符串,如何将其转换为URL安全 - 然后“un convert”它?PHP:使随机字符串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; 
} 

它只适用的权利,如果输入的功能是有效bin2hex字符串。如果我发送的东西不是bin2hex的结果,它就会死亡。我似乎无法让它在发生问题时抛出异常。

任何建议我可以做什么?我没有设置使用hex2bin/bin2hex。所有我需要能够将随机字符串转换为URL安全字符串,然后颠倒过程。

+2

[urlencode]是否有问题(http://php.net/manual/en/function.urlencode.php)/ [urldecode](http://php.net/manual/en/function.urldecode .PHP)? –

回答

8

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

$randomString = ...; 

$urlSafe = urlencode($randomString); 

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