問題描述
使用 sha256_password 時如何使用 PHP 的 mysqli 連接到 MySQL(訪問被拒絕) (How do you connect to MySQL using PHP's mysqli when using sha256_password (access denied))
我正在使用 MySQL 5.7.24 和 PHP 7.2.10。MySQL 配置了 SSL。我有一個用戶 my_user
,密碼為 abc123
。我嘗試使用兩個身份驗證插件進行配置:
ALTER USER 'my_user'@'192.168.192.150' IDENTIFIED WITH sha256_password BY 'abc123';
ALTER USER 'my_user'@'192.168.192.150' IDENTIFIED WITH mysql_native_password BY 'abc123';
從我的 PHP 服務器,我可以使用 mysql
命令行客戶端成功連接,而無需指定主機、用戶和密碼。但是,從 PHP 中,我只能在使用 mysql_native_password
時進行連接。使用 sha256_password
時不會。
以下 PHP 代碼適用於 mysql_native_password
:
$mysqli = mysqli_init();
$mysqli‑>options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$con = $mysqli‑>real_connect('192.168.192.100', 'my_user', 'abc123', 'my_db',
3306, null, MYSQLI_CLIENT_SSL | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT);
var_dump($mysqli‑>query('SELECT 1;'));
但是,當我使用 sha256_password
,我收到錯誤“拒絕用戶訪問”
參考解法
方法 1:
For what I understand from documentation, only one auth_option can be active at a time.
So when your are doing
ALTER USER 'my_user'@'192.168.192.150' IDENTIFIED WITH sha256_password BY 'abc123';
ALTER USER 'my_user'@'192.168.192.150' IDENTIFIED WITH mysql_native_password BY 'abc123';
your second resquest actually redefines sha256_password auth to mysql_native_password
(by Nick Williams、Will)