password_hash()
生成密码哈希,自带随机盐,是存密码的唯一推荐做法。
password_hash(string $password, string|int|null $algo = PASSWORD_DEFAULT, array $options = []): string
参数
| 参数 | 类型 | 说明 |
|---|---|---|
$password | string | 明文密码 |
$algo | string|int | PASSWORD_DEFAULT(bcrypt)或 PASSWORD_ARGON2ID |
$options | array | cost 等参数 |
返回值
string — 约 60 到 100 字符的哈希串,直接存数据库。
示例
$hash = password_hash('secret123', PASSWORD_DEFAULT);
echo substr($hash, 0, 7);输出
$2y$10$
注意
- 数据库字段至少 VARCHAR(255),换算法时不会截断。
- 不要自己加盐,函数已经做了。
- bcrypt 只处理前 72 字节,超长密码会被截断。