简体   繁体   中英

Redirect to login page unless a user is logged in

I'm trying to set up a page that is only accessible if a user is logged in and otherwise redirects to the login page.

I have the below function which I got from the book 'PHP and mySQL in In Easy Steps' but when no user is logged in it just hangs and does not redirect. I've checked for transcription errors and don't see any problem.

I've also tried using header() directly and I've also tried using ob_start() in case it was a problem with the header not being sent first - but still I can't get it to work and can't see what the problem is. Any guidance would be much appreciated!

<?php
    SESSION_START();

    function load($page='login.php') {
        $url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
        $url=rtrim($url,'/\\');
        $url.='/'.$page;
        header("Location:$url");
        exit();
    }

    if(!isset($_SESSION['userid'])) {
        load('login.php');
    }

    include_once('includes/header.html');
    /* ...rest of webpage...*/
    include_once('includes/footer.html');
?>

You have syntax error here in the below line:

if(!isset($_SESSION('userid'))) {

change to

if(!isset($_SESSION['userid'])) {

$_SESSION is an array not a function!

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