Home>Article>Backend Development> How to solve the 16-bit character garbled problem of PHP md5 function
php md5 16-bit character garbled solution: 1. Convert the output 16-byte binary into hexadecimal; 2. Use "substr(md5($str),8,16)" Method to obtain the 16-character md5 ciphertext.
Recommended: "PHP Video Tutorial"
garbled characters
PHP's md5 function is used to perform md5 operations on string parameters. This function has two parameters:
md5 ( string $str [, bool $raw_output = FALSE ] ) : string
The first parameter is the input string; the second parameter defaults to FALSE. When set to TRUE, a 16-bit md5 value can be output.
By default,
md5(string $str)
will return: a 32-character, hexadecimal hash value.
If you add the second parametermd5(string $str,TRUE)
, it will return: a hash value in original binary format with a length of 16 bytes.
From this we can see that when a binary format of 16 bytes length (corresponding to 16 characters, because it conforms to ASCII) is returned, since the browser characterizes it, it Garbled characters will be produced:
$str = "PHP"; echo "字符串:".$str."
"; echo "TRUE - 原始 16 字符二进制格式:".md5($str,TRUE)."
"; echo "FALSE - 32 字符十六进制格式:".md5($str)."
";
Solution
So how to get a 16-bit md5 value that is not garbled? There are two methods:
substr(md5($str),8,16)
. The second parameter and the third parameter represent starting from the 8th character (the subscript starts from 0), taking 16 characters.Here we use the second method to solve the problem of garbled characters. Still using the above example:
$str = "PHP"; echo "字符串:".$str."
"; echo "TRUE - 原始 16 字符二进制格式(乱码):".md5($str,TRUE)."
"; echo "TRUE - 原始 16 字符二进制格式(不乱码):".substr(md5($str),8,16)."
"; echo "FALSE - 32 字符十六进制格式:".md5($str)."
";
Note: If you need an uppercase md5 value, just use the strtoupper(...) function directly.
The above is the detailed content of How to solve the 16-bit character garbled problem of PHP md5 function. For more information, please follow other related articles on the PHP Chinese website!