使用 PHP 连接 MySQL 8.0 的时候,可能会发生如下错误:
SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client
错误原因是 MySQL 8 默认使用了新的密码验证插件:caching_sha2_password,而之前的 PHP (mysqlnd) 版本无法支持这种验证。
有两种方法可以解决这个问题。
- 升级 PHP 版本
- 使用 mysql_native_password
方法一:升级 PHP 版本
PHP 7.2.8 版本已经可以支持 caching_sha2_password,直接连接MySQL 8。
docker run --rm php:7.2.8 -i | grep caching_sha2_password
Loaded plugins => mysqlnd,debug_trace,auth_plugin_mysql_native_password,auth_plugin_mysql_clear_password,auth_plugin_caching_sha2_password,auth_plugin_sha256_password
但是需要注意的是:不知道是 Bug 还是 Feature,最新的 PHP 7.2.12 版本 和 PHP 7.3.0 版本都不支持 caching_sha2_password。
方法二:使用 mysql_native_password
修改 my.cnf 配置文件,设置默认密码验证插件为 mysql_native_password。
default-authentication-plugin=mysql_native_password
或者在 CREATE USER / ALTER USER 的时候设置账户的默认密码验证插件为 mysql_native_password。
CREATE USER 'user'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
ALTER USER 'user'@'localhost' IDENTIFIED WITH mysql_native_password;
参考:
1,075 total views, 1 views today