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

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

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

好的,所以我已成功在用户成功注册时将图像文件名存储到我的数据库中,我还成功地在注册时将个人资料图片存储到我的目录中。然而,我感到似乎在将用户个人资料图片存储在会话中时没有做正确的操作,因为该图像将在首页首次登录时显示,使用以下代码行...

  1. <?php
  2. echo $_SESSION['profile_img'];
  3. ?>

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

在主页上。以下是我的注册表单的PHP代码,以展示我如何处理数据。

  1. <?php
  2. include("config.php");
  3. $errors = [];
  4. $successMessage = "";
  5. session_start(); // 启动或恢复会话
  6. if (isset($_POST["submit"])) {
  7. // 检索表单数据
  8. $username = $_POST["username"];
  9. $email = $_POST["email"];
  10. $password = $_POST["password"];
  11. $profile_img = $_FILES["profile_img"]["name"];
  12. $profile_img_tmp = $_FILES["profile_img"]["tmp_name"];
  13. $confPassword = $_POST["confPassword"];
  14. $termsCheck = isset($_POST["termsCheck"]) ? 1 : 0; // 检查复选框是否选中
  15. // 验证表单数据
  16. if (empty($username)) {
  17. $errors["username"] = "用户名是必填项";
  18. }
  19. if (empty($email)) {
  20. $errors["email"] = "电子邮件是必填项";
  21. }
  22. if (empty($password)) {
  23. $errors["password"] = "密码是必填项";
  24. }
  25. if ($password !== $confPassword) {
  26. $errors["confPassword"] = "密码不匹配";
  27. }
  28. if (empty($profile_img)){
  29. $errors["profile_img"] = "选择个人资料图片";
  30. }
  31. if ($termsCheck !== 1) { // 检查复选框是否选中
  32. $errors["termsCheck"] = "您必须同意条款和条件";
  33. }
  34. // 如果没有验证错误,继续注册
  35. if (count($errors) === 0) {
  36. // 检查用户名是否已存在
  37. $stmt = mysqli_stmt_init($conn);
  38. $sql = "SELECT * FROM users WHERE username = ?";
  39. mysqli_stmt_prepare($stmt, $sql);
  40. mysqli_stmt_bind_param($stmt, "s", $username);
  41. mysqli_stmt_execute($stmt);
  42. $result = mysqli_stmt_get_result($stmt);
  43. if (mysqli_num_rows($result) > 0) {
  44. $errors["username"] = "用户名已存在";
  45. $errors["email"] = "电子邮件已存在";
  46. } else {
  47. // 检查电子邮件是否已存在
  48. $stmt = mysqli_stmt_init($conn);
  49. $sql = "SELECT * FROM users WHERE email = ?";
  50. mysqli_stmt_prepare($stmt, $sql);
  51. mysqli_stmt_bind_param($stmt, "s", $email);
  52. mysqli_stmt_execute($stmt);
  53. $result = mysqli_stmt_get_result($stmt);
  54. if (mysqli_num_rows($result) > 0) {
  55. $errors["email"] = "电子邮件已存在";
  56. } else {
  57. $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
  58. $created = date('Y-m-d H:i:s');
  59. $uploadDir = "profile_images/"; // 存储个人资料图片的目录
  60. $targetFilePath = $uploadDir . basename($profile_img);
  61. // 将上传的文件移动到目标目录
  62. if (move_uploaded_file($profile_img_tmp, $targetFilePath)) {
  63. // 文件移动成功
  64. $stmt = mysqli_stmt_init($conn);
  65. $sql = "INSERT INTO users (username, email, password, profile_img, created_at, terms_agreement) VALUES (?, ?, ?, ?, ?, ?)";
  66. mysqli_stmt_prepare($stmt, $sql);
  67. mysqli_stmt_bind_param($stmt, "sssssi", $username, $email, $hashedPassword, $targetFilePath, $created, $termsCheck);
  68. mysqli_stmt_execute($stmt);
  69. $successMessage = "注册成功!您现在可以登录。";
  70. $_POST = array(); // 清除表单数据
  71. // 在会话中设置profile_img
  72. $_SESSION['profile_img'] = $targetFilePath;
  73. } else {
  74. // 文件移动失败
  75. $errors["profile_img"] = "上传个人资料图片时出错";
  76. }
  77. }
  78. }
  79. }
  80. }
  81. ?>

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

以下是我的主页上的注销函数...

  1. <script>
  2. function logout() {
  3. // 发送到logout.php的AJAX请求
  4. var xhr = new XMLHttpRequest();
  5. xhr.open('GET', 'logout.php', true);
  6. xhr.onreadystatechange = function () {
  7. if (xhr.readyState === 4 && xhr.status === 200) {
  8. // 重定向到登录页面
  9. window.location.href = 'login.php';
  10. }
  11. };
  12. xhr.send();
  13. }
  14. </script>

And here is my logout.php...

以下是我的logout.php...

  1. <?php
  2. session_start(); // 启动会话
  3. session_destroy(); // 销毁会话
  4. // 重定向到登录页面
  5. header("Location: login.php");
  6. exit;
  7. ?>

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

  1. &lt;?php
  2. echo $_SESSION[&#39;profile_img&#39;];
  3. ?&gt;

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

  1. &lt;?php
  2. include(&quot;config.php&quot;);
  3. $errors = [];
  4. $successMessage = &quot;&quot;;
  5. session_start(); // Start or resume the session
  6. if (isset($_POST[&quot;submit&quot;])) {
  7. // Retrieve form data
  8. $username = $_POST[&quot;username&quot;];
  9. $email = $_POST[&quot;email&quot;];
  10. $password = $_POST[&quot;password&quot;];
  11. $profile_img = $_FILES[&quot;profile_img&quot;][&quot;name&quot;];
  12. $profile_img_tmp = $_FILES[&quot;profile_img&quot;][&quot;tmp_name&quot;];
  13. $confPassword = $_POST[&quot;confPassword&quot;];
  14. $termsCheck = isset($_POST[&quot;termsCheck&quot;]) ? 1 : 0; // Check if checkbox is checked
  15. // Validate form data
  16. if (empty($username)) {
  17. $errors[&quot;username&quot;] = &quot;Username is required&quot;;
  18. }
  19. if (empty($email)) {
  20. $errors[&quot;email&quot;] = &quot;Email is required&quot;;
  21. }
  22. if (empty($password)) {
  23. $errors[&quot;password&quot;] = &quot;Password is required&quot;;
  24. }
  25. if ($password !== $confPassword) {
  26. $errors[&quot;confPassword&quot;] = &quot;Passwords do not match&quot;;
  27. }
  28. if (empty($profile_img)){
  29. $errors[&quot;profile_img&quot;] = &quot;Choose a profile picture&quot;;
  30. }
  31. if ($termsCheck !== 1) { // Check if checkbox is checked
  32. $errors[&quot;termsCheck&quot;] = &quot;You must agree to the terms and conditions&quot;;
  33. }
  34. // If there are no validation errors, proceed with registration
  35. if (count($errors) === 0) {
  36. // Check if username already exists
  37. $stmt = mysqli_stmt_init($conn);
  38. $sql = &quot;SELECT * FROM users WHERE username = ?&quot;;
  39. mysqli_stmt_prepare($stmt, $sql);
  40. mysqli_stmt_bind_param($stmt, &quot;s&quot;, $username);
  41. mysqli_stmt_execute($stmt);
  42. $result = mysqli_stmt_get_result($stmt);
  43. if (mysqli_num_rows($result) &gt; 0) {
  44. $errors[&quot;username&quot;] = &quot;Username already exists&quot;;
  45. $errors[&quot;email&quot;] = &quot;Email already exists&quot;;
  46. } else {
  47. // Check if email already exists
  48. $stmt = mysqli_stmt_init($conn);
  49. $sql = &quot;SELECT * FROM users WHERE email = ?&quot;;
  50. mysqli_stmt_prepare($stmt, $sql);
  51. mysqli_stmt_bind_param($stmt, &quot;s&quot;, $email);
  52. mysqli_stmt_execute($stmt);
  53. $result = mysqli_stmt_get_result($stmt);
  54. if (mysqli_num_rows($result) &gt; 0) {
  55. $errors[&quot;email&quot;] = &quot;Email already exists&quot;;
  56. } else {
  57. $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
  58. $created = date(&#39;Y-m-d H:i:s&#39;);
  59. $uploadDir = &quot;profile_images/&quot;; // Directory to store profile images
  60. $targetFilePath = $uploadDir . basename($profile_img);
  61. // Move uploaded file to the target directory
  62. if (move_uploaded_file($profile_img_tmp, $targetFilePath)) {
  63. // File move success
  64. $stmt = mysqli_stmt_init($conn);
  65. $sql = &quot;INSERT INTO users (username, email, password, profile_img, created_at, terms_agreement) VALUES (?, ?, ?, ?, ?, ?)&quot;;
  66. mysqli_stmt_prepare($stmt, $sql);
  67. mysqli_stmt_bind_param($stmt, &quot;sssssi&quot;, $username, $email, $hashedPassword, $targetFilePath, $created, $termsCheck);
  68. mysqli_stmt_execute($stmt);
  69. $successMessage = &quot;Registration successful! You can now login.&quot;;
  70. $_POST = array(); // Clear form data
  71. // Set profile_img in session
  72. $_SESSION[&#39;profile_img&#39;] = $targetFilePath;
  73. } else {
  74. // File move failed
  75. $errors[&quot;profile_img&quot;] = &quot;Error uploading the profile picture&quot;;
  76. }
  77. }
  78. }
  79. }
  80. }
  81. ?&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...

  1. &lt;script&gt;
  2. function logout() {
  3. // Send an AJAX request to logout.php
  4. var xhr = new XMLHttpRequest();
  5. xhr.open(&#39;GET&#39;, &#39;logout.php&#39;, true);
  6. xhr.onreadystatechange = function () {
  7. if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) {
  8. // Redirect to the login page
  9. window.location.href = &#39;login.php&#39;;
  10. }
  11. };
  12. xhr.send();
  13. }
  14. &lt;/script&gt;

And here is my logout.php...

  1. &lt;?php
  2. session_start(); // Start the session
  3. session_destroy(); // Destroy the session
  4. // Redirect to the login page
  5. header(&quot;Location: login.php&quot;);
  6. exit;
  7. ?&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)

  1. &lt;?php
  2. session_start();
  3. include(&#39;config.php&#39;);
  4. if (isset($_SESSION[&#39;username&#39;])) {
  5. header(&quot;location: home.php&quot;);
  6. exit();
  7. }
  8. $username = $password = &quot;&quot;;
  9. $name_err = $password_err = &quot;&quot;;
  10. $max_login_attempts = 3; // Maximum number of login attempts allowed
  11. $wait_time_minutes = 15; // Time to wait in minutes before allowing login again
  12. if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) {
  13. // Validate username
  14. if (empty(trim($_POST[&quot;username&quot;]))) {
  15. $name_err = &quot;Please enter your username.&quot;;
  16. } else {
  17. $username = trim($_POST[&quot;username&quot;]);
  18. }
  19. // Validate password
  20. if (empty(trim($_POST[&quot;password&quot;]))) {
  21. $password_err = &quot;Please enter your password.&quot;;
  22. } else {
  23. $password = trim($_POST[&quot;password&quot;]);
  24. }
  25. // Check if there are no errors
  26. if (empty($name_err) &amp;&amp; empty($password_err)) {
  27. // Perform login authentication
  28. $sql = &quot;SELECT username, password, login_attempts, last_attempt FROM users WHERE username = ?&quot;;
  29. $stmt = $conn-&gt;prepare($sql);
  30. $stmt-&gt;bind_param(&quot;s&quot;, $username);
  31. $stmt-&gt;execute();
  32. $stmt-&gt;store_result();
  33. if ($stmt-&gt;num_rows == 1) {
  34. $stmt-&gt;bind_result($id, $hashed_password, $login_attempts, $last_attempt);
  35. $stmt-&gt;fetch();
  36. // Check if the user is locked out due to too many login attempts
  37. if ($login_attempts &gt;= $max_login_attempts) {
  38. $time_diff = strtotime(date(&quot;Y-m-d H:i:s&quot;)) - strtotime($last_attempt);
  39. $minutes_passed = floor($time_diff / 60);
  40. if ($minutes_passed &gt;= $wait_time_minutes) {
  41. // Reset login attempts and last attempt
  42. $login_attempts = 0;
  43. $last_attempt = null;
  44. // Update the user&#39;s login details in the database
  45. $stmt = $conn-&gt;prepare(&quot;UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?&quot;);
  46. $stmt-&gt;bind_param(&quot;iss&quot;, $login_attempts, $last_attempt, $username);
  47. $stmt-&gt;execute();
  48. $stmt-&gt;close();
  49. } else {
  50. $password_err = &quot;Too many login attempts. Please try again after $wait_time_minutes minutes.&quot;;
  51. header(&quot;location: login.php?error=too_many_attempts&quot;);
  52. exit();
  53. }
  54. }
  55. // Verify the password
  56. if (password_verify($password, $hashed_password)) {
  57. // Password is correct
  58. // Reset login attempts and last attempt
  59. $login_attempts = 0;
  60. $last_attempt = null;
  61. // Update the user&#39;s login details in the database
  62. $stmt = $conn-&gt;prepare(&quot;UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?&quot;);
  63. $stmt-&gt;bind_param(&quot;iss&quot;, $login_attempts, $last_attempt, $username);
  64. $stmt-&gt;execute();
  65. // Store the username in session
  66. $_SESSION[&#39;username&#39;] = $username;
  67. // Redirect to the dashboard or another page
  68. header(&quot;location: home.php&quot;);
  69. exit();
  70. } else {
  71. // Password is incorrect
  72. $password_err = &quot;Invalid password.&quot;;
  73. $login_attempts++;
  74. $last_attempt = date(&quot;Y-m-d H:i:s&quot;);
  75. // Update the user&#39;s login details in the database
  76. $stmt = $conn-&gt;prepare(&quot;UPDATE users SET login_attempts = ?, last_attempt = ? WHERE username = ?&quot;);
  77. $stmt-&gt;bind_param(&quot;iss&quot;, $login_attempts, $last_attempt, $username);
  78. $stmt-&gt;execute();
  79. header(&quot;location: login.php?error=invalid_credentials&quot;);
  80. exit();
  81. }
  82. } else {
  83. $name_err = &quot;Username not found.&quot;;
  84. header(&quot;location: login.php?error=username_not_found&quot;);
  85. exit();
  86. }
  87. $stmt-&gt;close();
  88. }
  89. $conn-&gt;close();
  90. }
  91. ?&gt;

答案1

得分: -1

我找到了如何修复这个问题的方法。

我只需要在登录时添加存储会话profile_img的代码行,通过添加这个...

  1. $_SESSION['profile_img'] = $profile_img; <----
  2. $_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...

  1. $_SESSION[&#39;profile_img&#39;] = $profile_img; &lt;----
  2. $_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:

确定