2011-11-20 49 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