You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为password_hash()的第二个参数传入字符串形式的哈希算法变量?

如何动态传入字符串形式的哈希算法到password_hash()

你遇到的警告完全正常——PASSWORD_BCRYPT不是字符串,而是PHP预定义的整数常量(它的实际值是1),直接传字符串字面量肯定会触发类型不匹配的警告。要从数据库这类地方动态获取算法名称并传给password_hash(),有几个可靠的解决办法:

方法1:使用constant()函数转换字符串到常量值

constant()函数可以接收字符串形式的常量名称,返回对应的常量值,这是最直接的方案。别忘了先验证常量是否存在,避免传入无效字符串导致报错:

$password = '121@121';
$hash_method_str = 'PASSWORD_BCRYPT'; // 从数据库或配置中获取的字符串

// 先检查常量是否存在,防止无效输入
if (defined($hash_method_str)) {
    $hash_method = constant($hash_method_str);
    $password_encrypted = password_hash($password, $hash_method);
} else {
    // 兜底处理:用PHP默认的哈希算法
    $password_encrypted = password_hash($password, PASSWORD_DEFAULT);
}

方法2:配合password_algos()做更严谨的校验(PHP 7.4+)

如果你用的是PHP 7.4及以上版本,可以用password_algos()获取当前环境支持的所有哈希算法列表,进一步确保传入的算法是合法且可用的:

$password = '121@121';
$hash_method_str = 'PASSWORD_BCRYPT';
$supported_algos = password_algos();

// 将支持的算法名转换为常量名格式(比如 'bcrypt' → 'PASSWORD_BCRYPT')
$supported_constants = array_map(function($algo) {
    return "PASSWORD_" . strtoupper($algo);
}, $supported_algos);

// 验证输入的字符串是否在合法常量列表中
if (in_array($hash_method_str, $supported_constants)) {
    $hash_method = constant($hash_method_str);
    $password_encrypted = password_hash($password, $hash_method);
} else {
    $password_encrypted = password_hash($password, PASSWORD_DEFAULT);
}

为什么直接传字符串不行?

简单说:PHP的密码哈希算法常量都是整数类型,比如PASSWORD_BCRYPT = 1、PASSWORD_ARGON2I = 2。password_hash()的第二个参数明确要求传入整数类型的算法标识,你传字符串自然会触发类型不匹配的警告。

内容的提问来源于stack exchange,提问作者Dawid Walczyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:30:48