如何在SSL上使用mysqli连接 [英] How to use mysqli connection with SSL
问题描述
我正在尝试与我的phpdatabase建立安全连接
I'm trying to make a secure connection with my phpdatabase
我编写了以下代码:
<?php
// form filled?
if (isset($_POST['submit'])) {
$user = 'gebruiker';
$pass = 'gebruiker';
$db = new mysqli('localhost', $user, $pass, 'forum');
if (mysqli_connect_errno()) {
echo 'database doesnt work';
file_put_contents('MySQLiErrors.txt', date('[Y-m-d H:i:s]') . mysqli_connect_error() . "\r\n", FILE_APPEND);
exit();
} else {
$username = $_POST['username'];
$userspassword = $_POST['password'];
$salt = strrev($userspassword.substr(0,4));
$password = hash('sha512',$userspassword.$salt);
$statement = $db->prepare("SELECT id,username FROM user WHERE username = ? AND password = ?");
$statement->bind_param("ss", $username, $password);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
session_start();
$_SESSION["username"] = $username;
header("Location: forum.php");
} else {
$_SESSION['Error'] = "Invalid username or password";
}
}
$db->close();
}
?>
我还在php.net上阅读了有关ssl连接的一些信息,但我不知道在这种情况下如何实现此目的.
I also read something about ssl connections on php.net but I don't have any idea how to implement this in this case.
http://php.net/manual/en/mysqli.ssl- set.php
我的代码在fedora 21上运行,并且工作正常,但是接下来我想要的是使用SSL的安全连接.
My code is running on fedora 21 and it works fine but the next thing I want is an secure connection using SSL.
我希望有人能提供一个很好的解决方案!
I hope someone may have a great solution!
推荐答案
您不需要客户端证书和私钥,并且在大多数情况下,您不希望MySQL服务器验证客户端证书.
You do NOT need the client certificate and private key and in most cases you do NOT want MySQL server to verify the client certificate.
但是,客户端必须使用CA证书来验证服务器证书,以防止MITM.
Client however MUST verify server certificate using CA certificate to prevent MITM.
<?php
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true);
$mysqli->ssl_set(NULL, NULL, "/etc/ssl/certs/ca-bundle.crt", NULL, NULL);
$mysqli->real_connect('hostname', 'user', 'password', 'database');
$mysqli->close();
?>
这篇关于如何在SSL上使用mysqli连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!