解决PHP 5应用连接MySQL 8的兼容性问题
在维护基于PHP 5.6的遗留Laravel应用时,若后端连接的MySQL数据库被其他部门升级至版本8,应用可能因兼容性问题而无法正常工作。以下是典型错误及解决方案。
常见连接错误
当PHP代码尝试连接MySQL 8服务器时,可能会遇到以下错误:
(HY000/2054): Server sent charset unknown to the client.The server requested authentication method unknown to the client [caching_sha2_password]
这些错误的根本原因是MySQL 8更改了默认配置:认证插件默认为caching_sha2_password,默认字符集为utf8mb4,而旧版PHP客户端可能无法识别这些新设置。
解决方案
1. 修改用户认证方式
将数据库用户的认证插件改为旧版PHP支持的mysql_native_password。
- 为新用户设置:
CREATE USER 'app_user'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_secure_password';
- 为现有用户修改:
ALTER USER 'app_user'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_secure_password';
2. 调整MySQL服务器配置
在MySQL配置文件(如my.cnf或my.ini)的[mysqld]部分添加以下设置:
[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8
default-authentication-plugin = mysql_native_password
修改配置后,需重启MySQL服务使更改生效。
通过上述步骤,可以恢复PHP 5应用程序与MySQL 8数据库之间的正常连接。