function shortUrl($long_url){ $key = '123'; $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 利用md5演算法方式產生hash值 $hex = hash('md5', $long_url.$key); $hexLen = strlen($hex); $subHexLen = $hexLen / 8; $output = array(); for($i=0;$i<$subHexLen;$i++){ // 將這32位分成四份,每一份8個字元,將其視作16進位串與0x3fffffff(30位1)與操作 $subHex = substr($hex, $i*8, 8); $idx = 0x3FFFFFFF & (1 * ('0x' . $subHex)); // 這30位分成6段, 每5個一組,算出其整數值,然後映射到我們準備的62個字元 $out = ''; for($j=0;$j<6;$j++){ $val = $idx & 0x0000003D; $out .= $base32[$val]; $idx = $idx >> 5; } $output[$i] = $out; } // 產生位元 return $output;}print_r( shortUrl('http://www.google.com/') );
php5.6輸出結果為:
Array( [0] => MVvIZz [1] => qURRjy [2] => U7rIzu [3] => JNNJbi)
php7輸出結果為:
Array( [0] => aaaaaa [1] => aaaaaa [2] => aaaaaa [3] => aaaaaa)
這是哪的問題?
回複內容:
function shortUrl($long_url){ $key = '123'; $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 利用md5演算法方式產生hash值 $hex = hash('md5', $long_url.$key); $hexLen = strlen($hex); $subHexLen = $hexLen / 8; $output = array(); for($i=0;$i<$subHexLen;$i++){ // 將這32位分成四份,每一份8個字元,將其視作16進位串與0x3fffffff(30位1)與操作 $subHex = substr($hex, $i*8, 8); $idx = 0x3FFFFFFF & (1 * ('0x' . $subHex)); // 這30位分成6段, 每5個一組,算出其整數值,然後映射到我們準備的62個字元 $out = ''; for($j=0;$j<6;$j++){ $val = $idx & 0x0000003D; $out .= $base32[$val]; $idx = $idx >> 5; } $output[$i] = $out; } // 產生位元 return $output;}print_r( shortUrl('http://www.google.com/') );
php5.6輸出結果為:
Array( [0] => MVvIZz [1] => qURRjy [2] => U7rIzu [3] => JNNJbi)
php7輸出結果為:
Array( [0] => aaaaaa [1] => aaaaaa [2] => aaaaaa [3] => aaaaaa)
這是哪的問題?
問題主要出現在這句話上
$idx = 0x3FFFFFFF & (1 * ('0x' . $subHex));
因為在php7
中,十六進位的字串不再被認為是數字
,所以這裡所採用的隱式轉換變成了無效轉換,導致結果出現了問題。
可以將此句替換為
$idx = 0x3FFFFFFF & hexdec($subHex);