PHP CODER
PHP CODER

Reputation: 1613

Redirection using header() not working properly while checking session

I have the problem with header..

I am working on login functionality... in that

1)If the user logged in with his/her credentials...

2)After that user try to open new tab and type the LoginViewController.php..

3)Here i need to redirect the user to previous logged in page..based on seesion active ..

4)But the header is not redirecting to loggedin.php page.. and showing some blank page..

 Here is the LoginViewController.php

 <?php
 session_start();
 include('GenericClasses/GenericCollectionClass.php');
 include('Models/UsersModel.php');
 include('DataObjects/Users.php');
 include('DatabaseAccess/DBHandler.php');

     if(!empty($_SESSION['user']))// Here checking session is empty or not
        {
            header("Location : loggedin.php");// Here it is not redirecting properly
            die();
        }
        else 
         {       

         }?>

Here is loggin.php

<?php
  session_start();
  header("Cache-Control: private, must-revalidate, max-age=0");
  header("Pragma: no-cache");
  header("Expires: Fri, 4 Jun 2010 12:00:00 GMT");
  include('GenericClasses/GenericCollectionClass.php');
  include('Models/UsersModel.php');
  include('DataObjects/Users.php');
  include('DatabaseAccess/DBHandler.php');

      if(!isset($_SESSION['user']))
         {
           header('Location: LoginViewController.php');
           exit();
          }
          echo '<div style="background:white; text-align:right"> Login  as:'.$_SESSION['user'].'<a href="LogoutViewController.php" style="text-align:right">Logout</a></div>';
         ?>


Any suggestions are acceptable... 

Upvotes: 0

Views: 520

Answers (3)

alwaysLearn
alwaysLearn

Reputation: 6950

Didnt went through the code but at first glance to your question I can suggest you three things ..

  1. session_start() should be first line after <?php

  2. Make sure noting is getting outputted before header() . It won't work then.

    From documentation

    Remember that header() must be called before any actual output is sent, 
    either by normal HTML tags, blank lines in a file, or from PHP. 
    
  3. Try enabling output buffering using ob_start after session_start and flush it in end using ob_flush

Upvotes: 1

Andy  Gee
Andy Gee

Reputation: 3342

session_start(); should be the fist line. Also you can't do a redirect after any content has been output, this includes any trailing space from the included files.

Upvotes: 2

Pramod Kumar Sharma
Pramod Kumar Sharma

Reputation: 8012

Put the session_start() on the top. It should be first on first line and remove unnecessary space from the code.

Upvotes: 0

Related Questions