萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

解決 MySQL 錯誤:mysqlnd cannot connect to MySQL 4.1+ using old insecure authentication

升級 PHP 至 5.3+ 後,舊專案呼叫 mysql_connect() 會拋出警告:

PHP Warning: mysql_connect(): mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password'). This will store a new, and more secure, hash value in mysql.user. If this user is used in other scripts executed by PHP 5.2 or earlier you might need to remove the old-passwords flag from your my.cnf file.

根本原因

  • MySQL 5.0 為相容 4.1 前版本,mysql.user 表的 Password 欄位儲存 16 位雜湊值。
  • PHP 5.3 起採用 mysqlnd 驅動,要求 41 位雜湊值進行驗證。
  • 若 my.cnf 設定 old_passwords=1,PASSWORD() 函數僅產生 16 位雜湊,導致驗證失敗。

解決步驟

  1. 登入 MySQL:mysql -u root -p
  2. 執行以下指令將 root 密碼重新雜湊為 41 位:
SET old_passwords = 0;
UPDATE mysql.user SET PASSWORD = PASSWORD('phpddt.com') WHERE User = 'root' LIMIT 1;
SELECT LENGTH(PASSWORD) FROM mysql.user WHERE User = 'root';  -- 應回傳 41
FLUSH PRIVILEGES;

補充說明

  • 若其他舊系統仍需 16 位雜湊,可建立專用帳號並設定 old_passwords=1 的 session,或修改 my.cnf 移除 old_passwords 旗標後重啟服務。
  • 長期建議:遷移至 mysqli 或 PDO_MySQL,並啟用 caching_sha2_password(MySQL 8.0+ 預設)以獲得更強安全性。

完成上述步驟後,PHP 即可正常連線,不再出現舊式驗證警告。

copyright © 萬盛學電腦網 all rights reserved