Question

I am having an infinite loop issue with this code. It's checking to see if there is a session variable, if there isn't, I want them to be redirected to the index page.

session_start();
   if (! isset($_SESSION['foo'])) {
     header('Location: /index.php');
   }
exit;

I've tried putting the exit; and exit(); and endif; outside the if loop and inside, all are still giving me the issue of infinite loops. This code is located in the header page, which is then called on every page, so you can only access the index page if you are not logged in. That's the gist of why I want this code to exist in the first place.

Thank you for your help in advance.

Was it helpful?

Solution

Add something to your if statement that would exclude the index.php page. Something like

if(! isset($_SESSION['foo']) && strpos($_SERVER['REQUEST_URI'], 'index.php') === false) {
    header('Location: /index.php');
}

OTHER TIPS

If you make that check on the index page, it will redirect loop whenever a session is not set. You need to make sure this check is not made on index.php

I think you're just missing session_start();

page.php :

<?php
session_start(); // this is important
if (! isset($_SESSION['foo'])) {
    header('Location: /index.php');
    exit;
}
?>

index.php :

<?php
session_start(); // this is important

//stuff

$_SESSION['foo'] = 'stuff';

//other stuff
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top