tags:

views:

205

answers:

3

I am currently re-writing my functions script (PHP) for my login system. Is the below code safe and a "good" way to check if the user is logged in?

    function loggedin()
    {
        $ID = ($_SESSION['ID']);
        $sql = "SELECT `online` FROM `users` WHERE `ID` = '$ID'";
        $result=mysql_query($sql);
        $count=mysql_num_rows($result);
        $row = mysql_fetch_array( $result );
        if ( $count== 1)
        {
            if ($_SESSION['ID'] && $_SESSION['session_id'])

            {
                if ( $row['online']== 1)
                    return 1;
            }
        }
        else
        {
            return 0;

        }
    }
+9  A: 

Beware Bobby Tables!

$ID = mysql_real_escape_string($_SESSION['ID']);

Escape any and all input parameters with mysql_real_escape_string()

Or better yet, use parameterized queries with (MySQL)PDO

Mike B
+1 for parameterized queries.
Daniel Pryden
Oh yes thanks I forgot about that. about PDO I dont really know how to use it, I will look into it in the future I really just want to get a safe working login system. Thanks
Elliott
@Elliott, NP. PDO might have a bit of a learning curve (not as bad as you might think) but after you get over that hurdle I think the readability benefit alone justifies its use.
Mike B
+5  A: 

It's definitely worth adding

session_regenerate_id(true);

to prevent session fixation.

So this

if ( $row['online']== 1)
    return 1;

becomes this:

if ( $row['online']== 1)
{
    session_regenerate_id(true);
    return 1;
}
seengee
Thanks, just been reading that article =D
Elliott
+2  A: 

In addition to other answers, make sure you check if the session exists first.

function loggedin()
{
    if(!isset($_SESSION['ID'])) return 0;
    $ID = ($_SESSION['ID']);
    ..
vise
oh yes, thanks for that.
Elliott