How to ignore session if a session had already been started?

I have a login page, and when I log in, it brings me to my home page. If the user doesn't log out and come back later, then he won't need to log in again. However, if a user is already logged in, then it will display an error message saying that a session has already been started and therefore, it's ignoring the following code.

This is my session.php file. I would like to add an if statement, saying that if the session is already started, then bring the user to the home page, and if the session is not started, then bring the user to the login page.

<?php
// mysqli_connect() function opens a new connection to the MySQL server. 
$conn = mysqli_connect("localhost", "root", "", "supercar"); 
session_start();// Starting Session
// Storing Session 
$user_check = $_SESSION['login_user']; 
// SQL Query To Fetch Complete Information Of User 
$query = "SELECT * from adminlogin where email = '$user_check'"; 
$ses_sql = mysqli_query($conn, $query); 
$row = mysqli_fetch_assoc($ses_sql); 
$login_session = $row['nom'];
$login_session2 = $row['id'];
$login_session3 = $row['motdepasse'];

?>

5 answers

  • answered 2019-04-15 05:52 Jaydip Kharvad

    try this code:

    if(!isset( $_SESSION['login_user'])){
       $_SESSION['login_user'];
    } else {
       header("location:index.php");
    }
    

  • answered 2019-04-15 05:56 SAVe

    Try this

    $user = $_SESSION['login_user'];
    if(isset($user) && $user != ''){
       $query = "SELECT * from adminlogin where email = '$user'"; 
       $ses_sql = mysqli_query($conn, $query); 
       $row = mysqli_fetch_assoc($ses_sql); 
       $login_session = $row['nom'];
       $login_session2 = $row['id'];
       $login_session3 = $row['motdepasse'];
    }else{
       header("location:index.php");
    }
    

  • answered 2019-04-15 06:04 danish-khan-I

    Answers above can do the trick but you also need to check for session. if session is running and you go the web page where session_start() exists you'll get error Use the code below.

    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    

    checkout here session here

  • answered 2019-04-15 06:21 Mayank Dudakiya

    empty() function will check that variable set or not with value empty or not. So you no need to compare it's value. If value vary then you need to compare values.

    if(!empty($_SESSION['login_user'])):
       // Your session is already set
    else:
       // Your session is not set yet
    endif;
    

  • answered 2019-04-15 06:31 PHP Geek

    Try this:

    if(empty($SESSION['login_user'])){
      session_start(); //Start session and put session value
    }else{
      //Redirect here
    }