Connect to Remote MySQL Server with SSL from PHP
Connecting to a remote MySQL server using SSL from PHP can be challenging, especially when using the outdated mysql_connect function. To overcome this challenge, it's recommended to utilize the MySQL Improved Extension (MySQLi), which offers enhanced functionality and SSL support.
Using MySQLi
The following PHP code demonstrates how to establish an SSL-encrypted connection using MySQLi:
ini_set('error_reporting', E_ALL); ini_set('display_errors', '1'); error_reporting(E_ALL|E_STRICT); $db = mysqli_init(); mysqli_options($db, MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true); $db->ssl_set('/etc/mysql/ssl/client-key.pem', '/etc/mysql/ssl/client-cert.pem', '/etc/mysql/ssl/ca-cert.pem', NULL, NULL); $link = mysqli_real_connect($db, 'ip', 'user', 'pass', 'db', 3306, NULL, MYSQLI_CLIENT_SSL); if (!$link) { die('Connect error (' . mysqli_connect_errno() . '): ' . mysqli_connect_error() . "\n"); } else { $res = $db->query('SHOW TABLES;'); print_r($res); $db->close(); }
PDO_MYSQL SSL Support
Using PDO_MYSQL with SSL requires a recent PHP version that supports SSL. For versions earlier than 5.3.8, SSL options are ignored. However, the following code sample illustrates SSL configuration with PDO_MYSQL:
$pdo = new PDO('mysql:host=ip;dbname=db', 'user', 'pass', array( PDO::MYSQL_ATTR_SSL_KEY => '/etc/mysql/ssl/client-key.pem', PDO::MYSQL_ATTR_SSL_CERT => '/etc/mysql/ssl/client-cert.pem', PDO::MYSQL_ATTR_SSL_CA => '/etc/mysql/ssl/ca-cert.pem' )); $statement = $pdo->query("SHOW TABLES;"); $row = $statement->fetch(PDO::FETCH_ASSOC); echo htmlentities($row['_message']);
By following these steps and adapting the provided code to your specific environment, you can successfully establish a secure connection to a remote MySQL server using SSL from PHP.
The above is the detailed content of How to Securely Connect to a Remote MySQL Server Using SSL in PHP?. For more information, please follow other related articles on the PHP Chinese website!