PHP: Setting the session information in a cookie w

2019-07-29 04:03发布

问题:

I have a very simple php single page, that requires the user to insert a specific username and pass in order to access its contents. It generates a cookie that allows the user to access that page for one day. If the user is logged in, the list of contents appear. If it's not, it shows the form.

It is all inside a single index.php page.

This single "protected" page contains a form where the user can put some information and save it. After the user logs in, all the content is shown as intended. But when the user tries to submit that form and reloads the page (the new content should be added to that page), it gets kicked out and the information contained in the form gets lost, and it's not saved.

This are the specific parts of the index.php page:

<?php session_start(); ?>
<!DOCTYPE html>
[...]

<?php 
if(isset($_POST['loguearse'])) { 
  $_SESSION['user']=strip_tags($_POST['user']);
  $_SESSION['pass']=strip_tags($_POST['pass']);
    if($_SESSION['user'] == 'myuser' && $_SESSION['pass'] == 'mypass') {
      if (isset($_SESSION['user'])) {
      session_start();
                setcookie ("usuario",$_POST['user'], time()+24*60*60);
                setcookie ("clave",$_POST['pass'], time()+24*60*60);
      }

[HERE IT GOES THE CONTENT THAT WORKS OK IF I STRIP THE LOGIN CONTROL]

  }
    } else { 
                    setcookie("usuario","");
                    setcookie("clave","");

      echo '
            <form method="post">
              <div class="form-group">
                <input type="text" class="form-control" name="user" id="user" placeholder="Usuario">
              </div>
              <div class="form-group">
                <input type="password" class="form-control" name="pass" id="pass" placeholder="clave">
              </div>
              </div>
              <div class="modal-footer">
                <input type="submit" name="loguearse" class="btn btn-primary">
              </div>
            </div>
            </form>
      ';
      echo 'No puedes entrar sin poner la clave correcta!';
    } 
?>

My question is: How do I keep that user logged in and with an active session for 24 hours?

回答1:

Your testing order is the problem here. You are originally testing for the POST variable, not the SESSION variable. Try this:

  1. Test for logout to see if the user tried to logout. If so, delete the session.

  2. Test for the session variables to indicate they're already logged in.

  3. IF 1 and 2 are false, test for login. If so, initialize session.



回答2:

It's the way you construct your if-conditions. Every time the user doesn't submit a post form you overwrite the cookie. The condition isset($_SESSION['user']) has to be on the highest level (at first) and then the post form check.

Also you run twice session_start(), one time is enough.



回答3:

I use this for this exact thing and just include this in the header of any page.

<?php
@session_start();
// DB DEFINITIONS
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
$db = db_connect();

if(isset($_GET['logout'])){ 
    session_unset();
    session_destroy();
    if (isset($_COOKIE['cookuhash']) && isset($_COOKIE['cookfhash'])){
        setcookie("cookuhash", "", time()-2592000,"/");
        setcookie("cookfhash", "", time()-2592000,"/");
        $uhash=$db->real_escape_string($_COOKIE['cookuhash']);
        $fhash=$db->real_escape_string($_COOKIE['cookfhash']);
        $db->query("DELETE FROM tblsessions WHERE USER_HASH='$uhash' AND FORM_TOKEN='$fhash'");
    }
    header("Location: /index.php");
    exit();
}

if(!isset($_SESSION['loggedIn'])){
    $_SESSION['loggedIn']=false;
    $_SESSION['username'] = 'Anonymous';
    $_SESSION['userid'] = 0;
    $_SESSION['userlevel'] = 0;
    $_SESSION['formToken'] = sha1(microtime());
}

if (!$_SESSION['loggedIn'] && isset($_COOKIE['cookuhash']) && isset($_COOKIE['cookfhash'])){
    $uhash=$db->real_escape_string($_COOKIE['cookuhash']);
    $fhash=$db->real_escape_string($_COOKIE['cookfhash']);
    $result = $db->prepare("SELECT u.id,uname, lvl, user_lvl_expires FROM tblusers u LEFT JOIN tblsessions s ON s.USER_ID=u.ID WHERE USER_HASH='$uhash' AND FORM_TOKEN='$fhash'");
    $result->execute();
    $result->bind_result($id,$uname,$ads,$lvl,$expires);
    $result->store_result();
    if($result->num_rows > 0){
        while ($result->fetch()) {  
            $_SESSION['loggedIn']=true;
            $_SESSION['username'] = $uname;
            $_SESSION['userid'] = $id;
            $_SESSION['userlevel'] = $lvl;
            $_SESSION['expires'] = $expires;
            $_SESSION['formToken'] = sha1(microtime());
        }
    }
}
?>

Then in any page, just check:

@session_start();
if((!isset($_SESSION['loggedIn']) || $_SESSION['loggedIn']==0) && !isset($_COOKIE['cookuhash'])){
    header("Location: /login.php");
    exit();
}