会话在 PHP 中的页面刷新时被破坏 [英] Session is destroyed on page refresh in PHP
问题描述
我正在使用 PHP 开发 Web 应用程序,用户最初必须在其中登录并查看其内容.我正在使用 PHP 会话来维护状态.我遇到了以下问题:
I am developing a web application using PHP in which a user initially has to sign in and view his content. I am using PHP sessions to maintain state. I encountered following problems:
- 尽管我在每个页面上启动了会话,并且在设置了相关会话变量后,每次刷新页面或在不同选项卡上浏览相同 URL 时,会话都会被销毁.
- 当用户已登录浏览登录页面时,我需要将用户重定向到他的内容页面.
我对 PHP 很陌生,所以我不知道如何解决这些问题.我在stackoverflow中提到了几个问题,但他们都说会话不会在页面刷新时被破坏.我不明白我的页面有什么问题.非常感谢任何带有解释的解决方案.
I'm really new to PHP, So I have no idea how to solve these problems. I referred several questions in the stackoverflow, but they all say that sessions are not destroyed on page refresh. I could not understand what's wrong with my page. Any solution with explaination is greatly appreciated.
登录页面
<?php
session_start();
class Sessions{
public static function setSessionState($userdata){
unset($userdata['password']);
unset($userdata['timestamp']);
$_SESSION['user']=$userdata;
}
}
if(isset($_POST['username']) && isset($_POST['password'])){
$dbcon = new DBConnection();
$dbcon->connect();
$username= strip_tags(stripslashes(trim($_POST['username'])));
$password = strip_tags(stripcslashes($_POST['password']));
echo "<script>alert($username);</script>";
$result = $dbcon->getUser($username,$password);
if(mysqli_num_rows($result)==1){
$user = $dbcon->getUserData($result); #getUserData function accepts mysqli result as an input and returns a row(array) of user details.
if(isset($user)){
Sessions::setSessionState($user);
header("location:index.php");
}
else{
echo "user variable is not set!!!";
}
}
else if(mysqli_num_rows($result)==0){
echo "Login error! Username or Password incorrect!";
}
else{
die("Unknown Error occured!");
}
}
............
索引页(用户隐私内容可见)
<?php
session_start();
if(isset($_SESSION['user'])){
print_r($_SESSION['user']);
}
else{
echo "session variable not set";
}
?>
谢谢.
推荐答案
我终于找到了实际上是我不好的答案.我没有提到 index.php 文件的最后一部分,因为我认为那部分无关紧要.在那部分我有一部分,
I finally found the answer which is actually my bad. I didn't mention the last part of the index.php file as I though that part is irrelevant.In that part I have a part,
<form action="<?php session_destroy(); ?>">
在评论 session_destroy() 方法调用后,我可以解决我的问题并使会话保持活动状态.
After commenting that session_destroy() method call, I could solve my problem and keep session alive.
抱歉代码不完整.
这篇关于会话在 PHP 中的页面刷新时被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!