How to connect mysql database over ssl in php?

Member

by darion , in category: PHP General , 5 months ago

How to connect mysql database over ssl in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 5 months ago

@darion 

To connect to a MySQL database using SSL in PHP, follow these steps:

  1. Enable SSL on the MySQL server: Open the MySQL configuration file typically located at /etc/mysql/my.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf. Add or uncomment the following lines in the [mysqld] section: ssl-ca=/path/to/ca-cert.pem ssl-cert=/path/to/server-cert.pem ssl-key=/path/to/server-key.pem Replace /path/to/ca-cert.pem, /path/to/server-cert.pem, and /path/to/server-key.pem with the actual paths to the Certificate Authority (CA) certificate, server certificate, and server private key files. Save the configuration file and restart the MySQL server.
  2. Verify that SSL is enabled on the MySQL server: Connect to the MySQL server via the command line: mysql -u
  3. Install the necessary SSL certificates on the PHP server: Copy the CA certificate, server certificate, and server private key files to a location accessible by the PHP script.
  4. Connect to the MySQL database using SSL in PHP:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php

$servername = "localhost";
$username = "your-username";
$password = "your-password";
$database = "your-database";

$mysqli = new mysqli($servername, $username, $password, $database, null, '/path/to/certificates');
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

echo "Connected successfully";

// Other database operations...

$mysqli->close();

?>


  • Replace localhost, your-username, your-password, your-database with the actual MySQL server hostname, username, password, and database name.
  • Replace /path/to/certificates with the actual path where you copied the SSL certificates.
  • Note: If you are using PDO instead of mysqli, you can refer to the official PDO documentation for connecting to a MySQL database using SSL.


Ensure that the PHP server has the necessary permissions to access the SSL certificate files.


That's it! You can now connect to your MySQL database over SSL using PHP.