How can you check if a PHP session exists?

前端 未结 11 1329
孤独总比滥情好
孤独总比滥情好 2021-02-04 06:11

Just wondering how to check if a PHP session exists... My understanding is that no matter what, if I am using sessions, I have to start my files with session_start() to even acc

11条回答
  •  盖世英雄少女心
    2021-02-04 07:04

    Store the session_id in $_SESSION and check against it.

    First time

    session_start();
    $_SESSION['id'] = session_id();
    

    Starts a session and stores the randomly given session id.

    Next time

    session_start();
    $valid_session = isset($_SESSION['id']) ? $_SESSION['id'] === session_id() : FALSE;
    if (!$valid_session) {
       header('Location: login.php');
       exit();
    }
    

    Starts a session, checks if the current session id and the stored session id are identical (with the ternary ? as replacement for the non-existing short circuit AND in php). If not, asks for login again.

提交回复
热议问题