php 如何循环遍历php中的会话数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5403721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:17:02  来源:igfitidea点击:

How to loop through session array in php

phpmysqlsession

提问by Wern Ancheta

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>

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

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

<?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/>";

?>

I get this:

我明白了:

enter image description here

在此处输入图片说明

While I'm expecting to get something like this:

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

User id: 1 Username: yoh

用户名:1​​ 用户名:yoh

User id: 2 Username: max

用户 id:2 用户名:max

回答by fabrik

$_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 仅对实际打开页面的访问者可用。(很高兴看到每个人的 $_SESSION 变量,不是吗?)

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

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

Update:

更新:

  • 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
  • 创建一个会话表,您可以在其中存储当前登录的用户
  • 每次登录用户打开页面时,增加一个值(时间戳),如 last_seen
  • 同时检查死会话(例如删除所有last_seen?value 小于now- 服务器会话生命周期的行

回答by Your Common Sense

Aside from extremely correct fabrik's answer, just a few lines on your code:

除了非常正确的 fabrik 的答案之外,您的代码中只有几行:

foreach($_SESSION as $sir){

}

this loop obviously does nothing. you can't get any output from the code that outputs nothing :)

这个循环显然什么都不做。您无法从不输出任何内容的代码中获得任何输出:)

Also, if you want to store multiple values into session, like in shopping cart, you have to store in in array, not long concatenated string:

此外,如果您想将多个值存储到会话中,例如在购物车中,您必须存储在数组中,而不是长连接字符串:

    $_SESSION['cart'][] =$result;

will produce an array called $_SESSION['cart'] which can be iterated the way you desired:

将生成一个名为 $_SESSION['cart'] 的数组,它可以按照您想要的方式进行迭代:

foreach ($_SESSION['cart'] as $result){
  echo "Item id: ".$result['id'].", name: ".$result['name']."<br>\n";
}

回答by Pere

session_start();
foreach ($_SESSION as $name => $value)
{
    echo $name."=".$value."<br>";
}

回答by Yoann

UPDATE: non numerical index.

更新:非数字索引。

In login.php

在登录.php

while($result=mysql_fetch_assoc($check)){
     $_SESSION[$result['Uname'].$result['ID']] = array(
         "uid"=>$result['ID'], 
         "uname"=>$result['Uname']
     );
}

And in you foreach

在你 foreach

foreach($_SESSION as $uinfos){
    echo "User id: ".$uinfos["uid"]."<br/>Username: ".$uinfos["uname"]."<br/>";
}

Like this you have only one entry for each user.

像这样,每个用户只有一个条目。

回答by sharpner

why don't you store it like

你为什么不把它储存起来

$_SESSION[$uid] = $name; or $_SESSION[] = array('uid' => $uid, 'name' => $name);

$_SESSION[$uid] = $name; 或 $_SESSION[] = array('uid' => $uid, 'name' => $name);

then you can simply iterate through all entries..

然后你可以简单地遍历所有条目..

foreach($_SESSION as $uid=> $name){
   ....
}

or

或者

foreach($_SESSION as $userArray){
    $uid = $userArray['uid']; 
    $name = $userArray['name']; 
}