Home > Software design >  How to prevent PHP SESSION closing when the page is refreshed?
How to prevent PHP SESSION closing when the page is refreshed?

Time:10-08

I have created Signup and Login systems for my gallery website. When a user tries to login into system, their user and password and admin privilege is checked. If it was successful, the username is appeared on top left corner of the home page and Login turns to Logout. The problem is that when I refresh the page, the user is logged out.

login.php code:

<?php

session_start();

class User

{

    public function CheckUser()

    {

        require "../app/core/database.php";

        if (isset($_POST['username']) && isset($_POST['pass'])) {

            $username = $_POST['username'];

            $password = $_POST['pass'];

            //to prevent sql injection

            $username = stripcslashes($username);

            $password = stripcslashes($password);

            $username = mysqli_real_escape_string($connection, $username);

            $password = mysqli_real_escape_string($connection, $password);

            $sql = "SELECT * FROM signup WHERE username = '$username' and password = '$password'";

            $sql2 = "SELECT 'admin' FROM signup";

            $log_result = mysqli_query($connection, $sql);

            $count = mysqli_num_rows($log_result);

            if ($count == 1) {

                $_SESSION['loggedin'] = true;

                $_SESSION['username'] = $username;

                $_SESSION['is_admin'] = mysqli_query($connection, $sql2);

                header("Location: ../home/index");

            } else {

                echo "<script>Invalid()</script>";

            }

        }

    }

}

?>

<script>

    function Invalid() {

        alert("Invalid user/password");

    }

</script> 

a part of home page code (index.php):

<?php

error_reporting(E_ALL);

ini_set('display_errors', TRUE);

include "../app/model/loadImages.php";

include "../app/core/config.php";

include "../app/model/login.php";

?>

<body>
  <nav>
    <?php while ($row = $result2->fetch_assoc()) {
      $rows[] = $row ?>
      <div class="logo">
        <a href="index.php"><?php echo $row['header_1'] ?> <em><?php echo $row['header_2'] ?></em></a>
        <span style="font-weight: normal; color:white;">
          <label>
            <?php
            if (isset($_SESSION['loggedin']) && isset($_SESSION['username'])) {
              echo $_SESSION['username'];
            } ?>
          </label>
        </span>
      </div>
      <div class="menu-icon">
        <span></span>
      </div>
      </nav>
 <section class="overlay-menu">
    <div class="container">
      <div class="row">
        <div class="main-menu">
          <ul>

            <li>
              <?php
              if (!isset($_SESSION['loggedin']) && !isset($_SESSION['username'])) {
                echo "<a href='/MyProject/public/login/index.php'>LogIn</a>";
              } else {
                echo "<a href='' action='EndSession();'>Logout</a>";
                echo "<li>";
                echo "<a href='/MyProject/public/admin/index'>Admin Area</a>";
                echo "</li>";
              } ?>

            </li>
            <li>
              <a href="about.html">About Us</a>
            </li>
            <li>
              <a href="blog.html">Blog Entries</a>
            </li>
            <li>
              <a href="single-post.html">Single Post</a>
            </li>
          </ul>
          <?php foreach ($rows as $row) { ?>
            <p><?php echo $row['message_1'] ?></p>
          <?php } ?>
        </div>
      </div>
    </div>
  </section>
<script>
    function EndSession() {

      <?php session_unset(); ?>
    }
  </script>

index.php for login page:

<?php
include "../app/core/config.php";
include "../app/model/login.php";

$login = new User();
$login->CheckUser();

?>

<body>
    
    <div class="limiter">
        <div class="container-login100" style="background-image: url('../../app/views/login/images/bg-01.jpg');">
            <div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-54">
                <form class="login100-form validate-form" method="POST">
                    <span class="login100-form-title p-b-49">
                        Login
                    </span>

                    <div class="wrap-input100 validate-input m-b-23" data-validate = "Username is reauired">
                        <span class="label-input100">Username</span>
                        <input class="input100" type="text" name="username" placeholder="Type your username">
                        <span class="focus-input100" data-symbol="&#xf206;"></span>
                    </div>

                    <div class="wrap-input100 validate-input" data-validate="Password is required">
                        <span class="label-input100">Password</span>
                        <input class="input100" type="password" name="pass" placeholder="Type your password">
                        <span class="focus-input100" data-symbol="&#xf190;"></span>
                    </div>
                    
                    <div class="text-right p-t-8 p-b-31">
                        <a href="#">
                            Forgot password?
                        </a>
                    </div>
                    
                    <div class="container-login100-form-btn">
                        <div class="wrap-login100-form-btn">
                            <div class="login100-form-bgbtn"></div>
                            <button class="login100-form-btn">
                                Login
                            </button>
                        </div>
                    </div>

                    <div class="txt1 text-center p-t-54 p-b-20">
                        <span>
                            Or Sign Up Using
                        </span>
                    </div>

                    <div class="flex-c-m">
                        <a href="#" class="login100-social-item bg3">
                            <i class="fa fa-google"></i>
                        </a>
                    </div>

                    <div class="flex-col-c p-t-155">
                        <span class="txt1 p-b-17">
                            Or Sign Up Using
                        </span>

                        <a href="<?php echo $root ?>/public/signup/index.php" class="txt2">
                            Sign Up
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

How can I fix this problem?

CodePudding user response:

I replicated the problem. The session_unset inside the js function is called when you refresh the page, besides it is inside a JS function.

Remove that funciton, than create a new file called logout.php:

<?php 
session_unset();
header("Location: ../home/index.php");
?>

Modify the a tag inside home/index.php:

<a href='logout.php'>Logout</a>

Side note: consider using session_destroy() instead of session_unset() for the logout

CodePudding user response:

You have to create session and setcookie , this method i hope helps you

First select validate the user : The password_verify funnction works if you store the password with bcrypt algorithm

  <?php
    if(isset($_POST["username"])) {
        $u = $dbmysqli->real_escape_string($_POST['username']);
        $p = $_POST['p'];



        $sql = $dbmysqli->prepare('SELECT username, password FROM users WHERE username = ?');
        $sql->bind_param("s", $u);
        $sql->execute();
        $sql->store_result();
    }
    if ($sql->num_rows > 0) {
        $sql->bind_result($db_id, $db_username, $db_pass_str);
        $sql->fetch();
        if (password_verify($p, $db_pass_str)) {
            // Verification success! User has logged-in!
            // Create sessions, so we know the user is logged in, they basically act like cookies but remember the data on the server.
            session_regenerate_id(TRUE);
            $_SESSION['userid'] = $db_id;
            $_SESSION['username'] = $db_username;
            $_SESSION['password'] = $db_pass_str;
            setcookie("id", $db_id, strtotime(' 30 days'), "/", "", "", TRUE);
            setcookie("user", $db_username, strtotime(' 30 days'), "/", "", "", TRUE);
            setcookie("pass", $db_pass_str, strtotime(' 30 days'), "/", "", "", TRUE);
            echo $db_username;
            exit();
        } else {
            // Incorrect password
            echo 'login_failed';
        }
    }
    ?>

Then you have to create a check login status file.php like this (include this in every page if you want user stay logged in) :

<?php
$user_ok = FALSE;
$log_id = "";
$log_username = "";
$log_password = "";

function evalLoggedUser($dbmysqli,$id,$u,$p){
    $sql = $dbmysqli->prepare('SELECT email FROM users WHERE id = ? AND uname = ? AND pswd = ?');
    $sql->bind_param("sss", $id,$u,$p);
    $sql->execute();
    $sql->store_result();
    $numrows = $sql->num_rows;
    if($numrows > 0){
        return true;
    }
}

if(isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"])) {
    $log_id = preg_replace('#[^0-9]#', '', $_SESSION['userid']);
    $log_username = preg_replace('#[^a-z0-9]#i', '', $_SESSION['username']);
    $log_password = $_SESSION['password'];
    //$log_password = preg_replace('#[^a-z0-9$./]#i', '', $_SESSION['password']);

    $user_ok = evalLoggedUser($dbmysqli,$log_id,$log_username,$log_password);
} else if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){
    $_SESSION['userid'] = preg_replace('#[^0-9]#', '', $_COOKIE['id']);
    $_SESSION['username'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['user']);
    $_SESSION['password'] = $_COOKIE['pass'];
    //$_SESSION['password'] = preg_replace('#[^a-z0-9$./]#i', '', $_COOKIE['pass']);
    $log_id = $_SESSION['userid'];
    $log_username = $_SESSION['username'];
    $log_password = $_SESSION['password'];

    $user_ok = evalLoggedUser($dbmysqli,$log_id,$log_username,$log_password);
    if ($user_ok == TRUE);
}
?>

And finally the logout.php :

<?php
session_start();
$_SESSION = array();
if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])) {
    setcookie("id", '', strtotime( '-5 days' ), '/');
    setcookie("user", '', strtotime( '-5 days' ), '/');
    setcookie("pass", '', strtotime( '-5 days' ), '/');
}
session_destroy();
if(isset($_SESSION['username'])){
    header("location: message.php?msg=Error:_Logout_Failed");
} else {
    header("location: login.php");
    exit();
}
?>
  • Related