内容:PHP中使用证书连接MySQL。
关于《MySQL安全连接以及使用证书访问》的配置这里不再介绍。
处于安全原因,或者其他的原因,访问数据库除了提供密码之外,还要求提供证书;
PHP 访问 MySQL 有三套API:
《关于 pdo、mysqli、mysql、mysqlnd、mysql client library 之间的关系》,点击查看;
mysqli
http://php.net/manual/zh/mysqli.ssl-set.php
(PHP 5, PHP 7)
当前到我的代码中使用的是 MySQLi API,所以主要记录 MySQLi 下使用证书。
mysqli_ssl_set 函数,来设置SSL链接;
mysqli::ssl_set
mysqli_ssl_set
(PHP 5, PHP 7)
mysqli::ssl_set — mysqli_ssl_set — Used for establishing secure connections using SSL
说明 ¶
面向对象风格
bool mysqli::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )
过程化风格
bool mysqli_ssl_set ( mysqli $link , string $key , string $cert , string $ca , string $capath , string $cipher )
Used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.
Note that MySQL Native Driver does not support SSL before PHP 5.3.3, so calling this function when using MySQL Native Driver will result in an error. MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5.3 onwards.
参数 ¶
link
仅以过程化样式:由mysqli_connect() 或 mysqli_init() 返回的链接标识。
key
The path name to the key file.
cert
The path name to the certificate file.
ca
The path name to the certificate authority file.
capath
The pathname to a directory that contains trusted SSL CA certificates in PEM format.
cipher
A list of allowable ciphers to use for SSL encryption.
Any unused SSL parameters may be given as NULL
返回值 ¶
This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.
mysql original
http://php.net/manual/en/mysql.constants.php#mysql.client-flags
关于一套API里,我只看到了一个常量 MYSQL_CLIENT_SSL ,鄙人暂时没找到使用方法;
pdo
http://php.net/manual/en/class.pdo.php
http://php.net/manual/en/ref.pdo-mysql.php
这个好说:
创建对象的时候,在 options 参数中提供即可:
<?php $pdo = new PDO( 'mysql:host=hostname;dbname=ssldb', 'username', 'password', array( PDO::MYSQL_ATTR_SSL_KEY =>'/path/to/client-key.pem', PDO::MYSQL_ATTR_SSL_CERT=>'/path/to/client-cert.pem', PDO::MYSQL_ATTR_SSL_CA =>'/path/to/ca-cert.pem' ) );