简体   繁体   中英

Using sessions & session variables in a PHP Login Script

I have just finished creating an entire login and register systsem in PHP, but my problem is I haven't used any sessions yet. I'm kind of a newbie in PHP and I've never used sessions before. What I want to do is, after the user registers and fills out the login form, they will still stay on the same page. So, there will be one part of the which will be if the session is logged_in and the other part will be else (the user is not logged in so display the login form). Can anyone tell me how to get started?

Begins the session, you need to say this at the top of a page or before you call session code

 session_start(); 

put a user id in the session to track who is logged in

 $_SESSION['user'] = $user_id;

Check if someone is logged in

 if (isset($_SESSION['user'])) {
   // logged in
 } else {
   // not logged in
 }

Find the logged in user ID

$_SESSION['user']

So on your page

 <?php
 session_start();


 if (isset($_SESSION['user'])) {
 ?>
   logged in HTML and code here
 <?php

 } else {
   ?>
   Not logged in HTML and code here
   <?php
 }

here is the simplest session code using php. We are using 3 files.

login.php

<?php  session_start();   // session starts with the help of this function 


if(isset($_SESSION['use']))   // Checking whether the session is already there or not if 
                              // true then header redirect it to the home page directly 
 {
    header("Location:home.php"); 
 }

if(isset($_POST['login']))   // it checks whether the user clicked login button or not 
{
     $user = $_POST['user'];
     $pass = $_POST['pass'];

      if($user == "Ank" && $pass == "1234")  // username is  set to "Ank"  and Password   
         {                                   // is 1234 by default     

          $_SESSION['use']=$user;


         echo '<script type="text/javascript"> window.open("home.php","_self");</script>';            //  On Successful Login redirects to home.php

        }

        else
        {
            echo "invalid UserName or Password";        
        }
}
 ?>
<html>
<head>

<title> Login Page   </title>

</head>

<body>

<form action="" method="post">

    <table width="200" border="0">
  <tr>
    <td>  UserName</td>
    <td> <input type="text" name="user" > </td>
  </tr>
  <tr>
    <td> PassWord  </td>
    <td><input type="password" name="pass"></td>
  </tr>
  <tr>
    <td> <input type="submit" name="login" value="LOGIN"></td>
    <td></td>
  </tr>
</table>
</form>

</body>
</html>

home.php

<?php   session_start();  ?>

<html>
  <head>
       <title> Home </title>
  </head>
  <body>
<?php
      if(!isset($_SESSION['use'])) // If session is not set then redirect to Login Page
       {
           header("Location:Login.php");  
       }

          echo $_SESSION['use'];

          echo "Login Success";

          echo "<a href='logout.php'> Logout</a> "; 
?>
</body>
</html>

logout.php

<?php
 session_start();

  echo "Logout Successfully ";
  session_destroy();   // function that Destroys Session 
  header("Location: Login.php");
?>

Firstly, the PHP documentation has some excellent information on sessions .

Secondly, you will need some way to store the credentials for each user of your website (eg a database). It is a good idea not to store passwords as human-readable, unencrypted plain text. When storing passwords, you should use PHP's crypt() hashing function. This means that if any credentials are compromised, the passwords are not readily available.

Most log-in systems will hash/crypt the password a user enters then compare the result to the hash in the storage system (eg database) for the corresponding username. If the hash of the entered password matches the stored hash, the user has entered the correct password.

You can use session variables to store information about the current state of the user - ie are they logged in or not, and if they are you can also store their unique user ID or any other information you need readily available.

To start a PHP session, you need to call session_start() . Similarly, to destroy a session and its data, you need to call session_destroy() (for example, when the user logs out):

// Begin the session
session_start();

// Use session variables
$_SESSION['userid'] = $userid;

// E.g. find if the user is logged in
if($_SESSION['userid']) {
    // Logged in
}
else {
    // Not logged in
}

// Destroy the session
if($log_out)
    session_destroy();

I would also recommend that you take a look at this . There's some good, easy to follow information on creating a simple log-in system there.

I always do OOP and use this class to maintain the session so u can use the function is_logged_in to check if the user is logged in or not, and if not you do what you wish to.

<?php
class Session
{
private $logged_in=false;
public $user_id;

function __construct() {
    session_start();
    $this->check_login();
if($this->logged_in) {
  // actions to take right away if user is logged in
} else {
  // actions to take right away if user is not logged in
}
}

public function is_logged_in() {
   return $this->logged_in;
}

public function login($user) {
// database should find user based on username/password
if($user){
  $this->user_id = $_SESSION['user_id'] = $user->id;
  $this->logged_in = true;
  }
}

public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}

private function check_login() {
if(isset($_SESSION['user_id'])) {
  $this->user_id = $_SESSION['user_id'];
  $this->logged_in = true;
} else {
  unset($this->user_id);
  $this->logged_in = false;
 }
}

}

$session = new Session();
?>
//start use session

$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
{

if($user=="user" && $pass=="pass")

{

$_SESSION['user']= $user;   

//if correct password and name store in session 

}
else {

echo "Invalid user and password";

header("Locatin:form.php");

}

if(isset($_SESSION['user'])) 

{

//your home page code here

exit;
}

Here's a single-page login / logout system example.
The password is never exposed, and the HASH+SALT is just as secure as anyone having a look at your database table with hash-salted passwords.

First, create a salted password $hash using this sandbox.io and make sure to replace the result String with the below $hash's ***

index.php single page:

<?php
// stackoverflow.com/a/67661402/383904
session_start();

$username = "pony";
$salt = "PonieshaveunicornS"; // Use something really custom instead of ponies
$hash = "***"; // Replace *** with the result of: echo hash("sha256", "myPassword".$salt);

$url = strtok($_SERVER["PHP_SELF"], '?');
$errorMessage = ""; // Used for login error messages


// LOGOUT SYSTEM
if (isset($_GET["p"]) && $_GET["p"] == "logout"):
    session_destroy();
    header("Location: $url");
    exit;
endif;


// LOGIN SYSTEM
if (isset($_POST['un']) && isset($_POST['pw'])):

  sleep(3); // Makes it ages slower for rainbow attacks

  if ($_POST['un'] == $username && hash("sha256", $_POST['pw'].$salt) == $hash):
    $_SESSION['_reg'] = $_POST['un'];
    header("Location: $url");
    exit;
  else:
    $message = "Incorrect login data";
  endif;
endif;


// DETERMINE A VALID LOGIN
$isLoggedIn = isset($_SESSION['_reg']) && $_SESSION['_reg'] == $username;


// YOUR CUSTOM LOGGED-IN METHODS AND STUFF
if ($isLoggedIn):

  // I.e: your DB connections, functions, methods, etc...

endif;
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My app</title>
</head>
<body>

  <div id="app">
    <?php if ($isLoggedIn): ?>
            
      <h1>Welcome <?= $_SESSION["_reg"] ?></h1>
      <a href="?p=logout">Logout</a>

    <?php else: ?>

      <h1>LogIn</h1>

        <form action="./index.php" method="post">
          <label><input type="text" name="un" placeholder="Username" /></label><br>
          <label><input type="password" name="pw" placeholder="Password"/></label><br>
          <input type="submit" id="submit" value="LOGIN" />
        </form>

        <b><?= $errorMessage ?></b>

    <?php endif; ?>
  </div>

</body>
</html>

Disclaimer: Be aware that the above

  • Is not that bad, but
  • should be improved using SHA rounds and/or a stronger algorithm than SHA256
  • never hardcode secrets (salts) or hashs into distributable files
  • is still susceptible to Session hijacking
  • It is exposable (Facebook'07 syndrome) by a malformatted/broken server file type response
  • is not professional (read: forbidden ) to push such code a public git repo with the exposed secret Salt and Hash
  • might be OK- ish for a short-term "Login to See something" project
  • you should never "just copy-paste" from Stack Overflow without a proper, deeper understanding of the provided code / scripts.
$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
  {    
    if($user=="user" && $pass=="pass")    
      {     
        $_SESSION['user']= $user;       
        //if correct password and name store in session 
    } else {
        echo "Invalid user and password";
        header("Locatin:form.php")
    }
if(isset($_SESSION['user']))     
  {
  }

You need to begin the session at the top of a page or before you call session code

session_start(); 
$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
{

if($user=="user" && $pass=="pass")

{

$_SESSION['user']= $user;   

//if correct password and name store in session 

}
else {

echo "Invalid user and password";

header("Locatin:form.php");

}

if(isset($_SESSION['user'])) 

{

//your home page code here

exit;
}

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