如何在php中循环遍历会话数组 [英] How to loop through session array in php

查看:95
本文介绍了如何在php中循环遍历会话数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历整个会话.但是我似乎无法获得预期的结果. 我仍在尝试探索.因此,请教我一个更好的方法.如果您发现我的代码不安全或不合适. 首先,我有以下登录表单:

I'm trying to loop through the session. But I can't seem to get the expected results. I'm still trying to explore things. So please teach me a better way to do this. If you find my code unsecure or inappropriate. First I have this login form:

<form name="x" action="login.php" method="post">

Username:<input type="text" name="uname" value=""></input><br/>
Password:<input type="password" name="pword" value=""></input>
<input type="submit" value="login"></input>
</form>

这是login.php,如果在mysql数据库中找到记录,它将设置会话:

And here's login.php which sets the session if the record is found on the mysql database:

<?php
require_once("conn.php");

$username=$_POST['uname'];
$pword=md5($_POST['pword']);

echo $username."<br/>";
echo $pword;

$check=mysql_query("SELECT * FROM users WHERE Uname='$username' AND Hpword='$pword'");

if(mysql_num_rows($check)==0){
    header('Location:loginform.php');
}else{

    session_start();

    while($result=mysql_fetch_assoc($check)){
        $_SESSION['uid'].=$result['ID'];
        $_SESSION['uname'].=$result['Uname'];


    }

}
?>

这是在会话中循环的文件:

And here's the file which loops through the session:

<?php

session_start();
echo "Logged in users:<br/>";


foreach($_SESSION as $sir){


}

echo "User id: ". $_SESSION['uid']."<br/>";
echo "Username: ".$_SESSION['uname']."<br/>";

?>

我明白了:

虽然我期望得到这样的东西:

While I'm expecting to get something like this:

用户ID:1 用户名:yoh

User id: 1 Username: yoh

用户ID:2 用户名:max

User id: 2 Username: max

推荐答案

$ _ SESSION仅适用于实际打开页面的访问者. (很高兴看到每个人的$ _SESSION变量,对吗?)

$_SESSION is available only for the visitor who opens the page actually. (It would be nice to see everyone's $_SESSION variables, isn't it?)

您可能希望将这些$ _SESSION变量存储在数据库中,然后遍历它们.

You may want to store these $_SESSION vars in your db then loop through them.

更新:

  • 创建一个会话表,您可以在其中存储当前登录的用户
  • 每次登录的用户打开页面时,都增加一个值(时间戳),如last_seen
  • 同时检查无效会话(例如,删除last_seen值小于now的所有行-服务器的会话寿命
  • create a sessions table where you can store your currently logged in users
  • every time when a logged in user opens a page, increment a value (timestamp) like last_seen
  • at the same time check dead sessions (e.g. delete all rows where last_seen value is smaller than now - server's session lifetime

这篇关于如何在php中循环遍历会话数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆