简体   繁体   中英

how to check if a user is logged on in php. beginner

using mysql as database. I got this code from the previous answers to the same question:

   session_start()):

   if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
   echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
  } else {
     echo "Please log in first to see this page.";
     }

Could you please explain what is: $_SESSION['loggedin'] . Where could I define it? the loggedin, please help

http://www.php.net/manual/book.session.php

I hope it will help you ;)

$_SESSION is a super-global array (available anywhere) that store all sessions variables.

session_start(); // begins session

$_SESSION['user_id'] = 99;

So, the loggedin variable is set to true when a user logged in, and then it is stored in the session. Sessions are basically information that are saved on the server.

$_SESSION is simply a persistent container where you can store anything and retrieve it in other requests during the same session. As such, you would have to set $_SESSION['loggedin'] and $_SESSION['username'] at the point where the user has successfully logged in.

After login:

$_SESSION['loggedin'] = true;

That's it.

You use sessions to store userdata to pass it between all pages that get loaded. You can define it as said by others by using the $_SESSION['sessionname'] var.

I will post a simple script below how to let people login on the website since you wanted to know how to use it:

session_start(); #session start alwas needs to come first

//Lets make sure scriptkiddies stay out
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

//Read the user from the database with there credentials
$query = mysql_query("select id from user where username = $username and password = $password");

//Lets check if there is any match
if(mysql_num_rows($query) > 0)
{
    //if there is a match lets make the sessions to let the user login
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $username;
}

This is a simple script how to use a Session for a login system. There are many other ways you can use sessions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM