問題描述
我正在嘗試與我的數據庫建立安全連接
I'm trying to make a secure connection with my database
我寫了以下代碼:
<?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() . "
", 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 a secure connection using SSL.
推薦答案
您不需要客戶端證書和私鑰,并且在大多數情況下,您不希望 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();
?>
這篇關于如何使用 mysqli 與 SSL 連接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!