英文:
Storing user data in the user session and retaining data after a successful logout
问题
Storing user profile image in user session and display on the users home page with every new session
用户个人资料图片存储在用户会话中,并在每个新会话中显示在用户的主页上
The issue is that the user profile image will display with the first login with an account that was just created. But after the user logs out and logs back in the profile image will not display.
问题在于用户个人资料图片将在刚刚创建的帐户的首次登录时显示。但是在用户注销并重新登录后,个人资料图片将不会显示。
Okay, so I've successfully stored the image file name into my database upon successful user registration, I've also successfully stored the profile image into my directory upon registration. However, I feel as though I didn't do something correct when it comes to storing the user's profile image within the session because the image will display on the home page on the first login with this line of code...
好的,所以我已成功在用户成功注册时将图像文件名存储到我的数据库中,我还成功地在注册时将个人资料图片存储到我的目录中。然而,我感到似乎在将用户个人资料图片存储在会话中时没有做正确的操作,因为该图像将在首页首次登录时显示,使用以下代码行...
<?php
echo $_SESSION['profile_img'];
?>
in the home page. Here is the PHP for my registration form to show you how I'm handling the data.
在主页上。以下是我的注册表单的PHP代码,以展示我如何处理数据。
<?php
include("config.php");
$errors = [];
$successMessage = "";
session_start(); // 启动或恢复会话
if (isset($_POST["submit"])) {
// 检索表单数据
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$profile_img = $_FILES["profile_img"]["name"];
$profile_img_tmp = $_FILES["profile_img"]["tmp_name"];
$confPassword = $_POST["confPassword"];
$termsCheck = isset($_POST["termsCheck"]) ? 1 : 0; // 检查复选框是否选中
// 验证表单数据
if (empty($username)) {
$errors["username"] = "用户名是必填项";
}
if (empty($email)) {
$errors["email"] = "电子邮件是必填项";
}
if (empty($password)) {
$errors["password"] = "密码是必填项";
}
if ($password !== $confPassword) {
$errors["confPassword"] = "密码不匹配";
}
if (empty($profile_img)){
$errors["profile_img"] = "选择个人资料图片";
}
if ($termsCheck !== 1) { // 检查复选框是否选中
$errors["termsCheck"] = "您必须同意条款和条件";
}
// 如果没有验证错误,继续注册
if (count($errors) === 0) {
// 检查用户名是否已存在
$stmt = mysqli_stmt_init($conn);
$sql = "SELECT * FROM users WHERE username = ?";
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) > 0) {
$errors["username"] = "用户名已存在";
$errors["email"] = "电子邮件已存在";
} else {
// 检查电子邮件是否已存在
$stmt = mysqli_stmt_init($conn);
$sql = "SELECT * FROM users WHERE email = ?";
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) > 0) {
$errors["email"] = "电子邮件已存在";
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$created = date('Y-m-d H:i:s');
$uploadDir = "profile_images/"; // 存储个人资料图片的目录
$targetFilePath = $uploadDir . basename($profile_img);
// 将上传的文件移动到目标目录
if (move_uploaded_file($profile_img_tmp, $targetFilePath)) {
// 文件移动成功
$stmt = mysqli_stmt_init($conn);
$sql = "INSERT INTO users (username, email, password, profile_img, created_at, terms_agreement) VALUES (?, ?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "sssssi", $username, $email, $hashedPassword, $targetFilePath, $created, $termsCheck);
mysqli_stmt_execute($stmt);
$successMessage = "注册成功!您现在可以登录。";
$_POST = array(); // 清除表单数据
// 在会话中设置profile_img
$_SESSION['profile_img'] = $targetFilePath;
} else {
// 文件移动失败
$errors["profile_img"] = "上传个人资料图片时出错";
}
}
}
}
}
?>
Here's my thoughts, I believe that this issue has something to do with my logout function that handles the session as well.
这是我的想法,我相信这个问题与处理会话的注销函数有关。
Here is the logout function in my home page...
以下是我的主页上的注销函数...
<script>
function logout() {
// 发送到logout.php的AJAX请求
var xhr = new XMLHttpRequest();
xhr.open('GET', 'logout.php', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 重定向到登录页面
window.location.href = 'login.php';
}
};
xhr.send();
}
</script>
And here is my logout.php...
以下是我的logout.php...
<?php
session_start(); // 启动会话
session_destroy(); // 销毁会话
// 重定向到登录页面
header("Location: login.php");
exit;
?>
Any thoughts on how I can achieve the desired effect? And again, what I'm trying to do is retain the user session data even after successfully logging out so that the user's profile image will still be visible to
英文:
Storing user profile image in user session and display on the users home page with every new session
The issue is that the user profile image will display with the first login with an account that was just created. But after the user logs out and logs back in the profile image will not display.
Okay, so I've successfully stored the image file name into my database upon successful user registration, I've also successfully stored the profile image into my directory upon registration. However I feel as though I didn't do something correct when it comes to storing the users profile image within the session because the image will display on the home page on the first login with this line of code...
<?php
echo $_SESSION['profile_img'];
?>
in the home page. Here is the PHP for my registration form to show you how I'm handling the data.
<?php
include("config.php");
$errors = [];
$successMessage = "";
session_start(); // Start or resume the session
if (isset($_POST["submit"])) {
// Retrieve form data
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$profile_img = $_FILES["profile_img"]["name"];
$profile_img_tmp = $_FILES["profile_img"]["tmp_name"];
$confPassword = $_POST["confPassword"];
$termsCheck = isset($_POST["termsCheck"]) ? 1 : 0; // Check if checkbox is checked
// Validate form data
if (empty($username)) {
$errors["username"] = "Username is required";
}
if (empty($email)) {
$errors["email"] = "Email is required";
}
if (empty($password)) {
$errors["password"] = "Password is required";
}
if ($password !== $confPassword) {
$errors["confPassword"] = "Passwords do not match";
}
if (empty($profile_img)){
$errors["profile_img"] = "Choose a profile picture";
}
if ($termsCheck !== 1) { // Check if checkbox is checked
$errors["termsCheck"] = "You must agree to the terms and conditions";
}
// If there are no validation errors, proceed with registration
if (count($errors) === 0) {
// Check if username already exists
$stmt = mysqli_stmt_init($conn);
$sql = "SELECT * FROM users WHERE username = ?";
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) > 0) {
$errors["username"] = "Username already exists";
$errors["email"] = "Email already exists";
} else {
// Check if email already exists
$stmt = mysqli_stmt_init($conn);
$sql = "SELECT * FROM users WHERE email = ?";
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) > 0) {
$errors["email"] = "Email already exists";
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$created = date('Y-m-d H:i:s');
$uploadDir = "profile_images/"; // Directory to store profile images
$targetFilePath = $uploadDir . basename($profile_img);
// Move uploaded file to the target directory
if (move_uploaded_file($profile_img_tmp, $targetFilePath)) {
// File move success
$stmt = mysqli_stmt_init($conn);
$sql = "INSERT INTO users (username, email, password, profile_img, created_at, terms_agreement) VALUES (?, ?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "sssssi", $username, $email, $hashedPassword, $targetFilePath, $created, $termsCheck);
mysqli_stmt_execute($stmt);
$successMessage = "Registration successful! You can now login.";
$_POST = array(); // Clear form data
// Set profile_img in session
$_SESSION['profile_img'] = $targetFilePath;
} else {
// File move failed
$errors["profile_img"] = "Error uploading the profile picture";
}
}
}
}
}
?>
Here's my thoughts, I believe that this issue has something to do with my logout function that handles the session as well.
Here is the logout function in my home page...
<script>
function logout() {
// Send an AJAX request to logout.php
var xhr = new XMLHttpRequest();
xhr.open('GET', 'logout.php', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Redirect to the login page
window.location.href = 'login.php';
}
};
xhr.send();
}
</script>
And here is my logout.php...
<?php
session_start(); // Start the session
session_destroy(); // Destroy the session
// Redirect to the login page
header("Location: login.php");
exit;
?>
Any thoughts on how I can achieve the desired effect? And again, what I'm trying to do is retain the user session data even after successfully logging out so that the users profile image will still be visible to the user the next time that they login.
(ADDED LOGIN PAGE CODE)
<?php
session_start();
include('config.php');
if (isset($_SESSION['username'])) {
header("location: home.php");
exit();
}
$username = $password = "";
$name_err = $password_err = "";
$max_login_attempts = 3; // Maximum number of login attempts allowed
$wait_time_minutes = 15; // Time to wait in minutes before allowing login again
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate username
if (empty(trim($_POST["username"]))) {
$name_err = "Please enter your username.";
} else {
$username = trim($_POST["username"]);
}
// Validate password
if (empty(trim($_POST["password"]))) {
$password_err = "Please enter your password.";
} else {
$password = trim($_POST["password"]);
}
// Check if there are no errors
if (empty($name_err) && empty($password_err)) {
// Perform login authentication
$sql = "SELECT username, password, login_attempts, last_attempt FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($id, $hashed_password, $login_attempts, $last_attempt);
$stmt->fetch();
// Check if the user is locked out due to too many login attempts
if ($login_attempts >= $max_login_attempts) {
$time_diff = strtotime(date("Y-m-d H:i:s")) - strtotime($last_attempt);
$minutes_passed = floor($time_diff / 60);
if ($minutes_passed >= $wait_time_minutes) {
// Reset login attempts and last attempt
$login_attempts = 0;
$last_attempt = null;
// Update the user's login details in the database
$stmt = $conn->prepare("UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?");
$stmt->bind_param("iss", $login_attempts, $last_attempt, $username);
$stmt->execute();
$stmt->close();
} else {
$password_err = "Too many login attempts. Please try again after $wait_time_minutes minutes.";
header("location: login.php?error=too_many_attempts");
exit();
}
}
// Verify the password
if (password_verify($password, $hashed_password)) {
// Password is correct
// Reset login attempts and last attempt
$login_attempts = 0;
$last_attempt = null;
// Update the user's login details in the database
$stmt = $conn->prepare("UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?");
$stmt->bind_param("iss", $login_attempts, $last_attempt, $username);
$stmt->execute();
// Store the username in session
$_SESSION['username'] = $username;
// Redirect to the dashboard or another page
header("location: home.php");
exit();
} else {
// Password is incorrect
$password_err = "Invalid password.";
$login_attempts++;
$last_attempt = date("Y-m-d H:i:s");
// Update the user's login details in the database
$stmt = $conn->prepare("UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?");
$stmt->bind_param("iss", $login_attempts, $last_attempt, $username);
$stmt->execute();
header("location: login.php?error=invalid_credentials");
exit();
}
} else {
$name_err = "Username not found.";
header("location: login.php?error=username_not_found");
exit();
}
$stmt->close();
}
$conn->close();
}
?>
答案1
得分: -1
我找到了如何修复这个问题的方法。
我只需要在登录时添加存储会话profile_img
的代码行,通过添加这个...
$_SESSION['profile_img'] = $profile_img; <----
$_SESSION['username'] = $username;
到登录脚本中。
英文:
Well, I figured out how to correct the issue..
All I needed to add was the line that stores the session profile_img upon logging in by adding this...
$_SESSION['profile_img'] = $profile_img; <----
$_SESSION['username'] = $username;
to the login script.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论