propatel
propatel

Reputation: 29

Cannot redirect properly in PHP

i have place this code in header file

if(isset($_SESSION) && isset($_SESSION['user'])){
    if($_SESSION['user'] == 'admin'){
        header('Location:admin.php');
        exit;
    }
    if($_SESSION['user'] == 'user'){
        header('Location:user.php');
        exit;
    }
}

My login file save session values like this

$result=$stmt->fetchAll();
$_SESSION['id'] = $result[0]->Id;
$_SESSION['user'] = 'user';

on index page header file works correctly but on user.php page it is giving error cannot redirect properly.

Actually problem is that on successful login it redirect to user page but it is checking again and again for session['user'] which is always 'user'. but redirecting on the same page user.php. i want a flag like thing to stop redirect it.

Upvotes: 1

Views: 206

Answers (2)

MatsLindh
MatsLindh

Reputation: 52792

First, this statement:

if(isset($_SESSION) && isset($_SESSION['user'])){

is equivalent to (and easier to read as) just:

if (isset($_SESSION['user'])) {

Second, you should only include this part of the code (the redirection) on your actual login page / controller. Since how it's written now, a logged in user will only be able to access admin.php or user.php.

Move the redirection code to login.php and keep it outside of your header file.

If that means changing the action of your login form to login.php, that's the correct part for the login code as well (and not in your header file).

Upvotes: 1

Conor Mancone
Conor Mancone

Reputation: 2030

If that code is in your header file, and user.php uses that header file, then you are stuck in an infinite redirect loop. You redirect to user.php who's header redirects you to user.php, etc... There doesn't appear to be any code that says "okay, stop redirecting now".

I would suggest one of a few things, in order of decreasing preference:

  1. Only redirect from the page that needs to redirect: don't put your redirect logic in the header.php file used by the entire site
  2. Once you redirect, set a flag denoting that the redirect has happened, and check for it before redirecting.
  3. Use a separate header file for the user.php that doesn't include the redirect.

Upvotes: 0

Related Questions