Home >Database >Mysql Tutorial >How Can I Securely Connect to a Remote MySQL Server Using SSL from PHP?
Connecting to a Remote MySQL Server with SSL from PHP
The question posed concerns establishing a secure connection to a remote MySQL server using SSL from PHP. The original code snippet employing mysql_connect yields an "SSL connection error."
Understanding the Issue
To delve into the root cause, consider the following:
To optimize security, MySQL configurations should include:
[client]
Secure communication can also be configured via PHP:
MySQLi Solution
To facilitate SSL connections using MySQLi, leverage the following code:
$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);
PDO_MYSQL Solution
If adherence to PDO_MYSQL is essential, employ this approach:
$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' ) );
Caution
Note that SSL support for PDO is limited in PHP versions prior to 5.3.8. For optimal functionality, consider upgrading to a more recent PHP release.
The above is the detailed content of How Can I Securely Connect to a Remote MySQL Server Using SSL from PHP?. For more information, please follow other related articles on the PHP Chinese website!