我正在尝试与我的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连接的内容,但我不知道如何在这种情况下实现这一点。
http://php.net/manual/en/mysqli.ssl-set.php
我的代码在fedora 21上运行,它工作正常,但我想要的是使用SSL的安全连接。
我希望有人可以有一个很好的解决方案!
答案 0 :(得分:6)
<?php
$con=mysqli_init();
if (!$con)
{
die("mysqli_init failed");
}
mysqli_ssl_set($con,"key.pem","cert.pem","cacert.pem",NULL,NULL);
if (!mysqli_real_connect($con,"localhost","my_user","my_password","my_db"))
{
die("Connect Error: " . mysqli_connect_error());
}
// Some queries...
mysqli_close($con);
?>
连接 - 必填。指定要使用的MySQL连接
对于mysql_real_connect,请使用
<?php
ini_set ('error_reporting', E_ALL);
ini_set ('display_errors', '1');
error_reporting (E_ALL|E_STRICT);
$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);
if (!$link)
{
die ('Connect error (' . mysqli_connect_errno() . '): ' . mysqli_connect_error() . "\n");
} else {
$res = $db->query('SHOW TABLES;');
print_r ($res);
$db->close();
}
?>
答案 1 :(得分:4)
您不需要客户端证书和私钥,并且在大多数情况下,您不希望MySQL服务器验证客户端证书。
但是,客户端必须使用CA证书来验证服务器证书,以防止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();
?>