简体   繁体   中英

How Check current PHP session set or unset

Guys in my php project i want to check on Login page session's status..if its unset i want user to login. ihave added this code to login page but it doesn't help as it loops.

if (strlen(session_id()) < 1) {
    ?>
    <script>window.location.href="login.php";</script>  
    <?php     
}
elseif(strlen(session_id()) > 1){ 
    ?>   
    <script>window.location.href="index.php";</script>   
    <?php 
}

Now other thing I want is if session is already started and if user manually tries to go on login page from address bar he should be redirected back to that current page.

If he is not logged in he should be redirected back to login page if he tries to open directly any page.

Also a new doubt with this is
Guys im using wamp server to run my PHP projects.I have used PHP sessions in my projects,Now when a user logins from one project the sessions get set and if on same pc if user open some other project which are not linked to each other he gets directly logged in without even doing it, if he logouts from one project he gets logout from all other project running on that pc.

Try this:

<?php
    session_start();
    if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == 1) {
        //session is set
        header('Location: /index.php');
    } else if(!isset($_SESSION['logged_in']) || (isset($_SESION['logged_in']) && $_SESSION['logged_in'] == 0)){
        //session is not set
        header('Location: /login.php');
    }
?>

In reply to above comments, yes you should create a session variable when the user is logged in. Edited code to reflect it.

you want to be checking for a particular session value, not the existence of a session ..

if ($_SESSION['logged_in']==1){

//
}else{

//
}

set $_SESSION['logged_in'] to 1 on log in and unset it (or set it to 0) on logout

  1. Remember to include session_start(); on the top of every page to get the values of variable SET in the SESSION through $_SESSION['example'], otherwise You will not be able to the session Variable values , OR

  1. A different Approach is to use session_start(); inside config.php file and include that file on the top of the code of every page where sessions are required otherwise U will not be able to get the value of SESSION variable..!!

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