Home > Article > Backend Development > PHP randomly generates a unique HASH value custom function, phphash custom function_PHP tutorial
There are many ways to obtain a random and unique HASH value on the Internet, but they are similar:
1. Get a random unique string first
2. Calculate HASH value using MD5 or sha1
A project needed to use hash values, so I went online to search, and found that PHP has a function that can directly generate unique strings - uniqid(). By using this function, plus the random number generated by yourself ( To prevent being cracked), it is more unique and difficult to guess. The main issues to consider are as follows:
1. Random efficiency and randomness: When choosing rand and mt_rand functions, mt_rand is the first choice, with high efficiency and good randomness;
2. Number of randomizations: Choose 5 times. Unniqid is originally unique. Adding randomness can only enhance security. 5 times is enough
3. md5 or sha1: Both can generate a unique hash value. The resource consumption of sha1 may be higher, but it is minimal. If you consider the lower case of database storage, you can use md5 (32-bit length)
<?php function get_hash(){ $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()+-'; $random = $chars[mt_rand(0,73)].$chars[mt_rand(0,73)].$chars[mt_rand(0,73)].$chars[mt_rand(0,73)].$chars[mt_rand(0,73)];//Random 5 times $content = uniqid().$random; // 类似 5443e09c27bf4aB4uT return sha1($content); } echo get_hash(); ?>