I tried to create a login page using javascript as seen below
我尝试使用如下所示的Java脚本创建登录页面
<script src="https://code.jquery.com/jquery-3.6.0.min.js">
function myfunction(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
jQuery.ajax({
type: "POST",
url: 'http://localhost/Gardening-System/select_user.php',
dataType: 'json',
data: {uname: username, psw: password },
success: function (obj, textstatus) {
if (!('error' in obj)) {
var user = obj.result; // Define user variable here
document.cookie = "username=" + username; // Set the cookie
window.alert("Logged in as: " + username); // Display the logged-in username in an alert
window.location.href = "index.html";
} else {
console.log(obj.error);
}
},
error: function (xhr, status, error) {
window.alert("AJAX request failed: " + error); // Handle AJAX request errors
}
});
}
</script>
This is select_user.php
which is to search the a database and checks whether the user exists. If they do, then it is supposed to return the username back to Javascript, which will then set the username as part of the cookie.
这是select_user.php,用于搜索数据库并检查用户是否存在。如果他们这样做,那么它应该将用户名返回给JavaScript,然后Javascript将用户名设置为cookie的一部分。
<?php
header('Content-type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$uname = $_POST['uname'];
$psw = $_POST['psw'];
// Database details
// Localhost address
$username = "root";
$password = "";
$dbname = "Gardening_System";
// Creating a connection
$con = mysqli_connect($host, $username, $password, $dbname);
// echo ("checkpoint 1");
// Ensuring connection is made
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
// Sanitize user inputs to prevent SQL injection
$uname = mysqli_real_escape_string($con, $uname);
$psw = mysqli_real_escape_string($con, $psw);
// Checking if the username and password combination exists in the database
$checkQuery = "SELECT * FROM Username_Password WHERE username= '$uname' AND password= '$psw'";
// mysqli_stmt_bind_param($stmt, "ss", $uname, $psw);
// mysqli_stmt_execute($stmt);
$checkResult = mysqli_query($con, $checkQuery);
// echo ("checkpoint 2");
if (mysqli_num_rows($checkResult) > 0) {
$userData = mysqli_fetch_assoc($checkResult);
$response = array('success' => true, 'result' => $userData["username"]);
echo json_encode($response);
// echo ("checkpoint 3");
if (setcookie($uname)){
header("Location: http://localhost/Gardening-System/index.html");
}
} else {
// Return an error message in JSON format
$response = array('error' => 'User does not exist');
echo json_encode($response);
}
mysqli_close($con);
} else {
// If the request method is not POST, return an error message
$response = array('error' => 'Invalid request method');
echo json_encode($response);
}
?>
After trying to login, it goes to the main screen, but it doesn't save the cookie and display it.
在尝试登录后,它会进入主屏幕,但不会保存并显示Cookie。
更多回答
You don't need to escape strings (using mysqli_real_escape_string
) when using prepared statements.
在使用预准备语句时,您不需要转义字符串(使用mysqli_realeESCRIPTING)。
This is very insecure if you want to use this as an authentication mechanism. Any user can just inject a random username in the cookie and try to continue on your webpage. Based on your example, I assume you are a novice, so the more secure approach would be to set a php server session with the username, so the backend stores the authentication instead. You will then get a php session_id in a cookie. That id will be used for php to know which session to use. In that session the username is stored (maybe even an expiration date). That way you know the user is authenticated.
如果您想将其用作身份验证机制,则这是非常不安全的。任何用户只需在Cookie中注入一个随机的用户名,然后尝试在您的网页上继续。根据您的示例,我假设您是新手,因此更安全的方法是使用用户名设置一个php服务器会话,以便后端存储身份验证。然后,您将在Cookie中获得一个php会话ID。该id将用于让php知道要使用哪个会话。在该会话中,用户名被存储(甚至可能是到期日期)。这样,您就知道用户已通过身份验证。
Also the way you are using cookies, you do not NEED a cookie. Just use localStorage
此外,您使用Cookie的方式,您不需要Cookie。使用localStorage
I would not do this. Use session. Also, hash your users passwords, dont store plain text.
我不会这么做的。使用会话。此外,散列您的用户密码,而不是存储纯文本。
Unrelated to question/issue but PHPMyAdmin is not a DB system. It is a UI generally for MySQL interactions.
与问题/问题无关,但PHPMyAdmin不是数据库系统。它通常是用于MySQL交互的UI。
我是一名优秀的程序员,十分优秀!