Proper configuration of PHP remote connection is a crucial step to ensure stable application operation, especially when deploying on a CentOS server. This article will guide you through the complete configuration process step by step.
Before starting, make sure PHP and MySQL are installed on your server. Check their versions with the following commands:
php -v
mysql -V
If not installed, use the command below to install PHP and its MySQL extension quickly:
<span class="fun">sudo yum install php php-mysql</span>
By default, MySQL only allows local connections. You need to modify the configuration to allow remote access.
Open the MySQL configuration file, usually located at /etc/my.cnf. Under the [mysqld] section, comment out or remove the bind-address setting to remove binding restrictions:
<span class="fun"># bind-address = 127.0.0.1</span>
Log into MySQL CLI and create a user that can access the database remotely:
<span class="fun">CREATE USER 'remote_user'@'%' IDENTIFIED BY 'password';</span>
Grant this user privileges on the specific database:
<span class="fun">GRANT ALL PRIVILEGES ON database_name.* TO 'remote_user'@'%';</span>
Flush privileges to apply changes:
<span class="fun">FLUSH PRIVILEGES;</span>
Ensure the firewall allows traffic through MySQL’s default port 3306 by running:
sudo firewall-cmd --permanent --add-port=3306/tcp
sudo firewall-cmd --reload
Use the following PHP script to test if the remote database connection works:
<?php
$servername = "your_remote_host";
$username = "remote_user";
$password = "password";
$database = "database_name";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection successful!";
?>
Upload this file to your server and access it. If you see “Connection successful!”, your remote connection setup is complete.
By following these steps, you have successfully configured PHP to remotely connect to MySQL on your CentOS server. This setup facilitates remote database management and improves system flexibility and scalability. Hopefully, this guide helps you achieve efficient remote database connections with ease.