Chandresh Mandaliya
Chandresh Mandaliya

Reputation: 29

ERR_TOO_MANY_REDIRECTS in PHP

My logout.php file is like this. Is there any mistake in my code

logout.php

<?php
session_start();
session_destroy();
header('Location:index.php');
exit;
?>

Here is my index.php file. If I am set $_SESSION['s_activId'] then it is working properly but when I am trying to put condition if $_SESSION['s_activId'] is not set at that time I want to pass header on index page sometimes it works sometimes it does not work.

<?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    header("Location:index.php");
}
else
{
  $wrong = '';
  if(isset($_POST['submit']))
  {
    $checkLogin = "SELECT userName,password,userType
                     FROM user
                    WHERE BINARY userName = '".$_POST['userName']."'
                      AND BINARY password = '".$_REQUEST['password']."'";
    $checkLoginresult = mysql_query($checkLogin);
    if($userLoginRow = mysql_fetch_array($checkLoginresult))
    {
      $_SESSION['s_activId']   = $userLoginRow['userName'];
      $_SESSION['s_password']  = $userLoginRow['password'];
      $_SESSION['hg_userType'] = $userLoginRow['userType'];
     
     if(!$_SESSION['s_urlRedirectDir'])
      {
        header("Location:index.php");
      }
      else
      {
        header("Location:reminder.php");
      }
    }
    else
    {
      $wrong = "UserId And Password Is Not Valid";
    }
  }
}
include("bottom.php");
$smarty->assign('wrong',$wrong);
$smarty->display("index.tpl");
?>

Upvotes: 1

Views: 10535

Answers (2)

Matas Lesinskas
Matas Lesinskas

Reputation: 444

Dont redirect index.php to index.php. you having redirects loop. Also if you have code below that also can fire add die in if because after redirect code below still executes. I didnt read your code, maybe there isnt problems with this but after

header("Location: lalala"); always add die(); or exit();

Upvotes: 0

Dileep Kumar
Dileep Kumar

Reputation: 1107

The problem arise in the condition below in index.php:

if(!isset($_SESSION['s_activId']))
{
    $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    header("Location:index.php");
}

When you logout, you are calling session_destroy() on logout.php and redirecting on index.php and the condition above gets true as s_activId is not set in session and again you are redirecting on index.php (without setting s_activId in session). The above condition will be true until the variable s_activId set in session and because of this you are getting ERR_TOO_MANY_REDIRECTS error.

The solution is, on index.php set the variable s_activId in session before calling the header method. Refer the code below:

if(!isset($_SESSION['s_activId']))
{
    $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    $_SESSION['s_activId'] = true;
    header("Location:index.php");
}

Upvotes: 1

Related Questions