简体   繁体   中英

Mysql PDO access denied for remote connection but Mysql CLI works

I am trying to connect to a remote Mysql server from my web server. I followed the following steps:

On the remote server:

1. “CREATE USER ’newremoteuser’@‘web-server_ip' IDENTIFIED BY 'remote_user_password’;”
2. “GRANT ALL PRIVILEGES ON *.* TO 'newremoteuser'@'web_server_ip’;”
3. “FLUSH PRIVILEGES;”

On the web server when I try to access using Mysql CLI, the connection is successful.

"mysql -u newremoteuser -h remote_server_ip -p"

However when I try to connect to remote server using PDO or Mysqli in PHP, I get the error

"FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access denied for user 'newremoteuser'@'my-domain-name.com' (using password: YES)'

Below is the PDO code

$REMOTEPDO = new PDO("mysql:host=$remote_server_ip;port=3306;dbname=$remote_db", $newremoteuser, $remote_user_password);
$REMOTEPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

I think it is denying access to 'newremoteuser'@'my-domain-name.com' as the remote user I added was 'newremoteuser'@'web-server_ip'. However, I can not find a solution to this. Can anyone please point me in the right direction?

Note: 'my-domain-name.com' is my website name hosted on my 'web_server_ip' server.

Remote server is Ubuntu 18 and Web server is Ubuntu 14.

As you've pointed out, changing the host for that user might fix your problem since the connection denial seems to be because of a host mismatch. Try updating the host for your existing user from the IP address to the domain name:

UPDATE mysql.user SET Host='my-domain-name.com' WHERE User='username';
FLUSH PRIVILEGES;

If it still doesn't work, it might be worth updating the host to '%' instead and seeing if it then lets you connect.

I just went through this. I could connect with command line but not PDO. My webserver client wouldn't connect until I enabled httpd_can_network_connect_db on the client server's SELinux and rebooted.

sudo setsebool -P httpd_can_network_connect_db 1

I forgot the reboot and chased my tail a bit longer than necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM