当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


PHP hash()用法及代码示例


定义和用法

这个hash()函数根据 (md5, sha256) 等算法返回给定数据的哈希值。返回值是一个带有十六进制(十六进制值)的字符串。

用法

hash ( string $algo , string $data [, bool $raw_output = FALSE ] ):string

参数

Sr.No 参数及说明
1

algo

哈希算法的名称。有一大堆可用于散列的算法,一些重要的算法是 md5、sha256 等。
要获得支持的算法的完整列表,请使用散列函数 hash_algos()

2

data

您希望生成散列的数据。请注意,一旦生成哈希,就无法逆转。

3

raw_output

默认情况下,该值为 false,因此它返回小写的十六进制值。如果值为真,它将返回原始二进制数据。

返回值

PHP hash() 函数返回一个带有小写十六进制的字符串。如果 raw_output 设置为 true,它将返回原始二进制数据。

PHP版本

此函数适用于 5.1.2 以上的 PHP 版本。

例子1

使用 md5 算法生成哈希值 -

<?php
   echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint');
?>

输出

这将产生以下结果 -

The hash of Welcome to Tutorialspoint is - 8ab923b97822bd258bf882e41de6ebff

例子2

使用 sha256 算法生成哈希值 -

<?php
   echo "The hash of Welcome to Tutorialspoint is - ". hash('sha256', 'Welcome to Tutorialspoint');
?>

输出

这将产生以下结果 -

The hash of Welcome to Tutorialspoint is - a6baf12546b9a5cf6df9e22ae1ae310b8c56be2da2e9fd2c91c94314eb0e5a2e

例子3

使用 crc32b 算法生成哈希 -

<?php
   echo "The hash of Welcome to Tutorialspoint is - ". hash('crc32b', 'Welcome to Tutorialspoint');
?>

输出

这将产生以下结果 -

The hash of Welcome to Tutorialspoint is - cd12151c

示例 4

生成 raw_output 为真的哈希 -

<?php
   echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint', true);
?>

输出

这将产生以下结果 -

The hash of Welcome to Tutorialspoint is - ��#�x"�%�������

相关用法


注:本文由纯净天空筛选整理自 PHP - hash() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。