Home > Database > Mysql Tutorial > body text

How Can I Securely Connect to a Remote MySQL Server Using SSL from PHP?

Barbara Streisand
Release: 2024-11-19 18:43:03
Original
1038 people have browsed it

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:

  • MySQLi (MySQL Improved Extension) offers superior support for encrypted connections compared to the legacy mysql_connect extension.
  • To optimize security, MySQL configurations should include:

    • [client]

      • ssl-ca = /etc/mysql/ssl/ca-cert.pem
      • ssl-cert = /etc/mysql/ssl/client-cert.pem
      • ssl-key = /etc/mysql/ssl/client-key.pem
  • Secure communication can also be configured via PHP:

    • mssql.secure_connection = On in php.ini

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);
Copy after login

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'
    )
);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template