Home > php教程 > php手册 > body text

PHP随机生成唯一HASH值自定义函数,phphash自定义函数

WBOY
Release: 2016-06-13 09:06:22
Original
929 people have browsed it

PHP随机生成唯一HASH值自定义函数,phphash自定义函数

网上有很多种方法获取随机唯一的HASH值,但是大同小异:

1、先获取随机的唯一字符串
2、进行MD5或者sha1算HASH值

一个项目要用到hash值,就去网上找了找,却发现PHP有一个函数能直接生成唯一字符串——uniqid(),通过使用这个函数,再加上自己生成的随机数(防止被破解),更具有唯一性且不易被猜解。主要考虑问题如下:

1、随机的效率与随机性:rand和mt_rand函数的选择,首选mt_rand,效率高,随机性好;
2、随机次数:选择5次,本来unniqid就是唯一的,加上随机的可以只是增强安全性,5次足矣
3、md5还是sha1:都能生成唯一的hash值,sha1占用资源可能高点,但是微乎其微,如果考虑数据库存储的小写,可以使用md5(32位长度)

<&#63;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();
&#63;>
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!