問題描述
我正在嘗試與我的數(shù)據(jù)庫(kù)建立安全連接
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 上閱讀了一些關(guān)于 SSL 連接的內(nèi)容,但我不知道如何在這種情況下實(shí)現(xiàn)這一點(diǎn).
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 上運(yùn)行并且運(yùn)行良好,但接下來我想要的是使用 SSL 的安全連接.
My code is running on fedora 21 and it works fine but the next thing I want is a secure connection using SSL.
推薦答案
您不需要客戶端證書和私鑰,并且在大多數(shù)情況下,您不希望 MySQL 服務(wù)器驗(yàn)證客戶端證書.
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 證書驗(yàn)證服務(wù)器證書以防止 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();
?>
這篇關(guān)于如何使用 mysqli 與 SSL 連接的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!