6

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

3
  • Try to avoid SQL injection or problems: use mysql_real_escape_string() when inserting POST data into a query Commented Mar 23, 2011 at 10:38
  • 1
    @Frosty only string data from any source it should be. Commented Mar 23, 2011 at 10:41
  • Obviously, however thanks for pointing this out for any beginner reading this. Commented Mar 23, 2011 at 10:46

5 Answers 5

6

$_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
Sign up to request clarification or add additional context in comments.

2 Comments

like make a table for current users? or make switches on user table?(1 if logged in, 0 if not). Is that what you want me to do?
just updated my answer with an outline on how to do this easily.
3

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

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:

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

Comments

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

1 Comment

The question suggests the output of every users session should be done. The correct anwer is that it cannot be done iterating over $_SESSION.
0

UPDATE : non numerical index.

In login.php

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

And in you 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.

3 Comments

$_SESSION array doesn't support numeric indices
it's still won't work, as PHP variable name cannot be started from number.
also, it's just a bad practice to iterate over $_SESSION itself. there can be (and most likely would be) other items, like shopping cart, user preferences etc
-1

why don't you store it like

$_SESSION[$uid] = $name; or $_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']; 
}

2 Comments

I think that if someone connects from another client (browser, machine...), this won't work...
$_SESSION array doesn't support numeric indices

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.