Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through session array in php

Tags:

php

mysql

session

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:

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

User id: 2 Username: max

like image 720
Wern Ancheta Avatar asked Mar 23 '11 10:03

Wern Ancheta


People also ask

Can PHP session store array?

Yes, PHP supports arrays as session variables.

How do you delete a session array?

We can remove items from the array by using array_diff() function. $_SESSION[cart]=array_diff($_SESSION[cart],$prod_id);


1 Answers

$_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?)

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

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
like image 57
fabrik Avatar answered Sep 19 '22 07:09

fabrik