在用户会话中存储用户数据,并在成功注销后保留数据。

huangapple go评论68阅读模式
英文:

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...

&lt;?php 
echo $_SESSION[&#39;profile_img&#39;]; 
?&gt;

in the home page. Here is the PHP for my registration form to show you how I'm handling the data.

&lt;?php
include(&quot;config.php&quot;);
$errors = [];
$successMessage = &quot;&quot;;
session_start(); // Start or resume the session
if (isset($_POST[&quot;submit&quot;])) {
// Retrieve form data
$username = $_POST[&quot;username&quot;];
$email = $_POST[&quot;email&quot;];
$password = $_POST[&quot;password&quot;];
$profile_img = $_FILES[&quot;profile_img&quot;][&quot;name&quot;];
$profile_img_tmp = $_FILES[&quot;profile_img&quot;][&quot;tmp_name&quot;];
$confPassword = $_POST[&quot;confPassword&quot;];
$termsCheck = isset($_POST[&quot;termsCheck&quot;]) ? 1 : 0; // Check if checkbox is checked
// Validate form data
if (empty($username)) {
$errors[&quot;username&quot;] = &quot;Username is required&quot;;
}
if (empty($email)) {
$errors[&quot;email&quot;] = &quot;Email is required&quot;;
}
if (empty($password)) {
$errors[&quot;password&quot;] = &quot;Password is required&quot;;
}
if ($password !== $confPassword) {
$errors[&quot;confPassword&quot;] = &quot;Passwords do not match&quot;;
}
if (empty($profile_img)){
$errors[&quot;profile_img&quot;] = &quot;Choose a profile picture&quot;;
}
if ($termsCheck !== 1) { // Check if checkbox is checked
$errors[&quot;termsCheck&quot;] = &quot;You must agree to the terms and conditions&quot;;
}
// If there are no validation errors, proceed with registration
if (count($errors) === 0) {
// Check if username already exists
$stmt = mysqli_stmt_init($conn);
$sql = &quot;SELECT * FROM users WHERE username = ?&quot;;
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, &quot;s&quot;, $username);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) &gt; 0) {
$errors[&quot;username&quot;] = &quot;Username already exists&quot;;
$errors[&quot;email&quot;] = &quot;Email already exists&quot;;
} else {
// Check if email already exists
$stmt = mysqli_stmt_init($conn);
$sql = &quot;SELECT * FROM users WHERE email = ?&quot;;
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, &quot;s&quot;, $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) &gt; 0) {
$errors[&quot;email&quot;] = &quot;Email already exists&quot;;
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$created = date(&#39;Y-m-d H:i:s&#39;);
$uploadDir = &quot;profile_images/&quot;; // 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 = &quot;INSERT INTO users (username, email, password, profile_img, created_at, terms_agreement) VALUES (?, ?, ?, ?, ?, ?)&quot;;
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, &quot;sssssi&quot;, $username, $email, $hashedPassword, $targetFilePath, $created, $termsCheck);
mysqli_stmt_execute($stmt);
$successMessage = &quot;Registration successful! You can now login.&quot;;
$_POST = array(); // Clear form data
// Set profile_img in session
$_SESSION[&#39;profile_img&#39;] = $targetFilePath;
} else {
// File move failed
$errors[&quot;profile_img&quot;] = &quot;Error uploading the profile picture&quot;;
}
}
}
}
}
?&gt;

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...

&lt;script&gt;
function logout() {
// Send an AJAX request to logout.php
var xhr = new XMLHttpRequest();
xhr.open(&#39;GET&#39;, &#39;logout.php&#39;, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) {
// Redirect to the login page
window.location.href = &#39;login.php&#39;;
}
};
xhr.send();
}
&lt;/script&gt;

And here is my logout.php...

&lt;?php
session_start(); // Start the session
session_destroy(); // Destroy the session
// Redirect to the login page
header(&quot;Location: login.php&quot;);
exit;
?&gt;

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)

&lt;?php
session_start();
include(&#39;config.php&#39;);
if (isset($_SESSION[&#39;username&#39;])) {
header(&quot;location: home.php&quot;);
exit();
}
$username = $password = &quot;&quot;;
$name_err = $password_err = &quot;&quot;;
$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[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) {
// Validate username
if (empty(trim($_POST[&quot;username&quot;]))) {
$name_err = &quot;Please enter your username.&quot;;
} else {
$username = trim($_POST[&quot;username&quot;]);
}
// Validate password
if (empty(trim($_POST[&quot;password&quot;]))) {
$password_err = &quot;Please enter your password.&quot;;
} else {
$password = trim($_POST[&quot;password&quot;]);
}
// Check if there are no errors
if (empty($name_err) &amp;&amp; empty($password_err)) {
// Perform login authentication
$sql = &quot;SELECT username, password, login_attempts, last_attempt FROM users WHERE username = ?&quot;;
$stmt = $conn-&gt;prepare($sql);
$stmt-&gt;bind_param(&quot;s&quot;, $username);
$stmt-&gt;execute();
$stmt-&gt;store_result();
if ($stmt-&gt;num_rows == 1) {
$stmt-&gt;bind_result($id, $hashed_password, $login_attempts, $last_attempt);
$stmt-&gt;fetch();
// Check if the user is locked out due to too many login attempts
if ($login_attempts &gt;= $max_login_attempts) {
$time_diff = strtotime(date(&quot;Y-m-d H:i:s&quot;)) - strtotime($last_attempt);
$minutes_passed = floor($time_diff / 60);
if ($minutes_passed &gt;= $wait_time_minutes) {
// Reset login attempts and last attempt
$login_attempts = 0;
$last_attempt = null;
// Update the user&#39;s login details in the database
$stmt = $conn-&gt;prepare(&quot;UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?&quot;);
$stmt-&gt;bind_param(&quot;iss&quot;, $login_attempts, $last_attempt, $username);
$stmt-&gt;execute();
$stmt-&gt;close();
} else {
$password_err = &quot;Too many login attempts. Please try again after $wait_time_minutes minutes.&quot;;
header(&quot;location: login.php?error=too_many_attempts&quot;);
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&#39;s login details in the database
$stmt = $conn-&gt;prepare(&quot;UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?&quot;);
$stmt-&gt;bind_param(&quot;iss&quot;, $login_attempts, $last_attempt, $username);
$stmt-&gt;execute();
// Store the username in session
$_SESSION[&#39;username&#39;] = $username;
// Redirect to the dashboard or another page
header(&quot;location: home.php&quot;);
exit();
} else {
// Password is incorrect
$password_err = &quot;Invalid password.&quot;;
$login_attempts++;
$last_attempt = date(&quot;Y-m-d H:i:s&quot;);
// Update the user&#39;s login details in the database
$stmt = $conn-&gt;prepare(&quot;UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?&quot;);
$stmt-&gt;bind_param(&quot;iss&quot;, $login_attempts, $last_attempt, $username);
$stmt-&gt;execute();
header(&quot;location: login.php?error=invalid_credentials&quot;);
exit();
}
} else {
$name_err = &quot;Username not found.&quot;;
header(&quot;location: login.php?error=username_not_found&quot;);
exit();
}
$stmt-&gt;close();
}
$conn-&gt;close();
}
?&gt;

答案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[&#39;profile_img&#39;] = $profile_img; &lt;----
$_SESSION[&#39;username&#39;] = $username;

to the login script.

huangapple
  • 本文由 发表于 2023年5月26日 09:16:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定