When connecting to a database using PHP, particularly with mysqli_connect() or PDO, a common error is:
Host 'xxx.xxx.xxx.xxx' is not allowed to connect to this MySQL server
This error message means that the database server has rejected the connection request from the current client host, primarily because the permissions on the database server do not allow the client IP address to connect.
This article will explain in detail how to troubleshoot and resolve this issue.
When MySQL server allows user connections, it not only verifies the username and password but also checks the host address from which the connection originates. In other words, even if the username and password are correct, the connection will be denied if the host is not authorized.
By default, MySQL only permits connections from localhost (the local machine); remote connections require additional configuration.
What hostname or IP is used when connecting? Typically, the PHP code looks like this:
$mysqli = new mysqli('db.m66.net', 'user', 'password', 'database');
Make sure that the hostname here is the correct IP or domain name of the database server.
To resolve the “Host not allowed to connect” problem, you need to grant permission to the specific client host on the MySQL server.
Assuming your database username is dbuser and you want to allow connections from the remote host IP 123.123.123.123:
GRANT ALL PRIVILEGES ON database.* TO 'dbuser'@'123.123.123.123' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
If you want to allow connections from all hosts (not recommended in production), you can use the % wildcard:
GRANT ALL PRIVILEGES ON database.* TO 'dbuser'@'%' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
By default, MySQL binds to 127.0.0.1, restricting access to the local machine only.
Open the MySQL configuration file (usually located at /etc/mysql/my.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf), find this line:
bind-address = 127.0.0.1
Change it to:
bind-address = 0.0.0.0
Then restart the MySQL service:
sudo service mysql restart
Ensure that the server firewall allows external access to MySQL’s default port 3306.
For example, using ufw:
sudo ufw allow 3306/tcp
Assuming the database server address is db.m66.net, here is a sample connection code:
<?php
$host = 'db.m66.net';
$user = 'dbuser';
$password = 'password';
$dbname = 'database';
<p>$mysqli = new mysqli($host, $user, $password, $dbname);</p>
<p>if ($mysqli->connect_error) {<br>
die('Connection failed: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);<br>
}</p>
<p>echo 'Connection successful!';</p>
<p>$mysqli->close();<br>
?><br>
Verify that the username and password are correct.
Ensure that the PHP and MySQL servers can communicate over the network. You can test this using ping or telnet db.m66.net 3306.
Check the database user permissions to confirm that the user has access to the specified database.
Review the MySQL error logs for more details.