2

I want to prevent user to access login page when its already logged in. In header page I've checked session so that user can't access any admin page without logging in. What code do I have to write in header page and session page to prevent user access login page while already logged in?

Here's my session class

public static function init(){
    session_start();
}
public static function set($key, $val){
    $_SESSION[$key]=$val;
}
public static function get($key){
    if (isset($_SESSION[$key])) {
        return $_SESSION[$key];
    } else {
        return false;
    }
}
public static function checkSession(){
    self::init();
    if (self::get("login")==false) {
        self::destroy();
        header("Location:login.php");
    }  
}

public static function destroy(){
    session_destroy();
J.Polok
  • 21
  • 4
  • 1
    Possible duplicate of [How to prevent multiple logins in PHP website](https://stackoverflow.com/questions/1727919/how-to-prevent-multiple-logins-in-php-website) – Ekown Feb 21 '19 at 05:18
  • if(isset($_SESSION)) { profile page } else { login page } – Sayed Mohd Ali Feb 21 '19 at 06:32

4 Answers4

1

Check the session variable value on login page if exist then redirect or dashboard or home page if not exist session variable value redirect on login page.

Nandit
  • 91
  • 7
1

Write your login page like this:

<?php
   session_start();
   if(isset($_SESSION['key'])){
      header('home.php');
   } else {
      //Paste login page code here
   }
?>
1

And this code avoid the user back to the page after log out

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

This code is to avoid repeated login from the user

if(isset($_SESSION['login_account_id'])){
      header('location: /index.php');
  }
John Cris Mañabo
  • 230
  • 1
  • 3
  • 24
0
<?php
// Initialize the session
session_start();

// If user is already logged in, redirect to index
if($_SESSION["loggedin"] == true){
    header("location: index.php");
}

?>
Jeffrey
  • 37
  • 9
  • While this code may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit](https://stackoverflow.com/posts/54804056/edit) your answer to add explanation, and give an indication of what limitations and assumptions apply. – tbraun89 Feb 21 '19 at 13:54
  • @tbraun89 this is why I added the `//` information. – Jeffrey Feb 21 '19 at 13:58