How can I check if a user is logged-in in php?

Viewed 263240

I'm pretty new to PHP and I am trying to figure out how to use sessions to check and see if a user is logged into a website so that they would have authorization to access specific pages.

Is this something that is complicated or is it because I am a noob that I can't figure it out?

8 Answers

You may do a session and place it:

// Start session
session_start();

// Check do the person logged in
if($_SESSION['username']==NULL){
    // Haven't log in
    echo "You haven't log in";
}else{
    // Logged in
    echo "Successfully logged in!";
}

Note: you must make a form which contain $_SESSION['username'] = $login_input_username;

Apart from the splendid answer von @hiburn8 what is missing is a secure why to logoff / logout. I realize this was not asked but should be considered as well.

Loging off should contain two elements:

  1. remove all data from the session variable
  2. reset the ID to prevent from session reuse attempts.

Perhaps 2) is not needed if all session data was destroyed but there might be (future) scenarios where this might be a good thing. Luckily PHP offers a function for both the elements and a complete code would be:

session_start();             // get a session to manipulate
session_unset();             // remove all server data on the session
session_regenerate_id(true); // create a new session id to prevent hijacking

This should typically go in a logoff script.

else if (isset($_GET['actie']) && $_GET['actie']== "aanmelden"){

    $username= $_POST['username'];
    $password= md5($_POST['password']);
    $query = "SELECT password FROM tbl WHERE username = '$username'";
    $result= mysql_query($query);
    $row= mysql_fetch_array($result);

    if($password == $row['password']){
            session_start();
            $_SESSION['logged in'] = true;
            echo "Logged in";

    }
}
Related