PHP, if session is started redirect to a different page

15,154

Solution 1

You need session_start.

session_start();
if(!isset($_SESSION['username'])) {
    header("Location: log.php");
    exit;
}

Solution 2

I think that you miss the call to php session_start(). Try this:

<?php
session_start();
if (isset($_SESSION['username'])) { header('Location: log.php'); }
?>

And be sure that your use logged account.

Share:
15,154

Related videos on Youtube

user3026386
Author by

user3026386

Updated on July 04, 2022

Comments

  • user3026386
    user3026386 almost 2 years
    <?php 
    1.
     if (isset($_SESSION['username'])) {
    header('Location: log.php');
    }
    
    2.
     if (session_id() != '') {
        header('Location: log.php');
    }
    3.
    if(isset($_SESSION['username']))
    {
        header("Location: log.php");
        exit;
    }
    
    4.
     if (session_status() != PHP_SESSION_NONE) {
        header("Location: log.php");
    }
    
    ?>
    

    I want my php to redirect to from main.php to log.php if the session is live. I want to achieve an effect where logged on users cannot access a page and once they try to do it via a url they get automatically redirected to a different page. Above are the attempts I did and did not work for me.

    • Paul
      Paul over 10 years
      I think you forgot to use (or mention) session_start();
    • sjagr
      sjagr over 10 years
      Did you make sure to use session_start()? There will never be a session in any subsequent pages as long as session_start hasn't been declared. Use the presence of $_SESSION variables in combination with a previously declared session_start to take care of this properly.