This web page has a redirect loop

Asked

Viewed 499 times

2

Well folks, after a long search on google, I found nothing similar to my problem, so I thought to report here.

Yesterday a system I am building started displaying this problem "This web page has a redirect loop". The server I’m using is XAMPP and the browser is Chrome.

At the time the problem happened, I was writing a pagination system and had logged into a login account to do some basic tests. Now every time I try to open the main page where the user type the password to log in appears "This web page has a redirect loop".

I tried some diagnostic suggested by Chrome, but nothing worked. I also deleted all code until the moment I know the system was working, but it also didn’t work.

Someone’s been through this before?

Here’s a piece of the code

Connection to the connected database

//Seleciona o banco de dados

$hostname = "localhost";
$username = "root";
$password = "";
$database = "sessao";

// as variáveis email e senha recebem os dados digitados na página anterior
$email = (isset($_POST['Email'])) ? $_POST['Email'] : $_SESSION['Email']; // se n tiver post, utiliza sessao
$senha = (isset($_POST['Senha'])) ? $_POST['Senha'] : $_SESSION['Senha']; // se n tiver post, utiliza sessao

//Conexão mysql
$conexao = mysql_connect($hostname, $username, $password) or die ("Erro na conexão do banco de dados.");

//Conexao com banco de dados
$selecionabd = mysql_select_db($database,$conexao) or die ("Banco de dados inexistente.");

//Comando SQL de verificação de autenticação
$tabela = "SELECT * FROM usuarios WHERE Email = '$email' AND Senha = '$senha'";

$resultado = mysql_query($tabela,$conexao) or die ("Erro na seleção da tabela.");

//Caso consiga logar cria a sessão 
if (mysql_num_rows ($resultado)) {

    $_SESSION['Email'] = $email;
    $_SESSION['Senha'] = $senha;
}

//Caso contrário redireciona para a página de autenticação
else{                                                             
    //Destrói
    session_destroy();

    //Limpa
    unset ($_SESSION['Email']);
    unset ($_SESSION['Senha']); 

    //Redireciona para a página de autenticação
    header('location:principal.php');

}

Pagina principa, principal.php

<html lang="pt-br">
<head>
     <meta charset="UTF-8">
     <title>Pagina Pricipal</title>
</head>
<body>
<?php include "conexao_sessao.php"; ?>

<form method="post" action="profile.php" >
<label>E-mail: </label>
<input type="text" name="Email" id="Email" /><br />
<label>Senha:</label>
<input type="password" name="Senha" id="Senha" /><br />
<input type="submit" value="Login"  />
<a href= "novo_usuario.php">Cadastre-se</a>
</body>
</html>

Page that opens after the user logs in, profile.php

<!DOCTYPE html>
<?php include "conexao_sessao.php";

if(isset($_GET['logout'])) {

    //Destrói
    session_destroy();

    //Limpa
    unset ($_SESSION['login']);
    unset ($_SESSION['senha']); 

    //Redireciona para a página de autenticação
    header('location:principal.php');

}
?>

<!DOCTYPE html>
<html lang="pt-br">
<body>
<head>
    <meta charsert="UTF-8"/>
    <title>Sistema de Comentários</title>
</head>
<a href="principal.php?logout=1">Sair</a>
</br>
</br>
<a href="responda.php">Clique aqui para responder perguntas!</a>
</br>
<a href="EditandoPerfil/editar_perfil.php">Editar Perfil!</a>
<hr>
</br>
<h3>Perguntas Respondidas</h3>
</br>
<hr>

<?php include("RespondaGlobal/mostrar.php"); ?>
</body>
</html>
  • Hello @Vandro-Auro, Welcome to Stack Overflow! If possible, post parts of your code so we can better assist you. You can start by taking a look at the places where you redirect to see if there is a bug that might be doing this (for example, a page that redirects to another page in an infinite loop due to a validation failure)

  • Put the code that checks the login. The part that checks the login session. It’s 90% sure the loop is in that snippet.

  • bingo.. that’s it.. connection_sessao.php shouldn’t be included that way.

  • @Danielomine why?

  • Try trading all include for include_once

1 answer

1

The loop de redirecionamento is created when a Location of a page generates a new Location.

For example:

index.php [Location: login.php] ->
login.php [Location: index.php] ->
index.php [Location: login.php] ->
login.php [Location: index.php] ->
Fim, loop de redirecionamento

This does not necessarily require two pages and may be the same, as in your case.

Cade the problem:

//Caso contrário redireciona para a página de autenticação
else{                                                             
    //Destrói
    session_destroy();

    //Limpa
    unset ($_SESSION['Email']);
    unset ($_SESSION['Senha']); 

    //Redireciona para a página de autenticação
    header('location:principal.php');

}

This section has the problem. The header('location:principal.php'); will always be triggered when the user loads the page, without even having typed/sent an email or password.

That is, every time you enter the page you send a Location: principal.php, when loading is sent a new Location: principal.php, generating a loop.

How to correct:

Start from the beginning by checking the need to run the script:

<?php
    //Seleciona o banco de dados

    $hostname = "localhost";
    $username = "root";
    $password = "";
    $database = "sessao";

    ## MODIFICAÇÃO

    if(isset($_POST['Email']) or isset($_SESSION['Email'])){

    ## FIM DA MODIFICAÇÃO

    // as variáveis email e senha recebem os dados digitados na página anterior
    $email = (isset($_POST['Email'])) ? $_POST['Email'] : $_SESSION['Email']; // se n tiver post, utiliza sessao
    $senha = (isset($_POST['Senha'])) ? $_POST['Senha'] : $_SESSION['Senha']; // se n tiver post, utiliza sessao

    //Conexão mysql
    $conexao = mysql_connect($hostname, $username, $password) or die ("Erro na conexão do banco de dados.");

    //Conexao com banco de dados
    $selecionabd = mysql_select_db($database,$conexao) or die ("Banco de dados inexistente.");

    //Comando SQL de verificação de autenticação
    $tabela = "SELECT * FROM usuarios WHERE Email = '$email' AND Senha = '$senha'";

    $resultado = mysql_query($tabela,$conexao) or die ("Erro na seleção da tabela.");

    //Caso consiga logar cria a sessão 
    if (mysql_num_rows ($resultado)) {

        $_SESSION['Email'] = $email;
        $_SESSION['Senha'] = $senha;
    }

    //Caso contrário redireciona para a página de autenticação
    else{                                                             
        //Destrói
        session_destroy();

        //Limpa
        unset ($_SESSION['Email']);
        unset ($_SESSION['Senha']); 

        //Redireciona para a página de autenticação
        header('location:principal.php');

    }

    ## MODIFICAÇÃO

    }

    ## FIM DA MODIFICAÇÃO
?>

A simple if(isset($_POST) or isset($_SESSION)){ will validate if there is a session or if there is a POST, that is, if someone typed/sent something.

This will return false and false, if a user is disconnected and has not sent anything, so it will also fall from the previously mentioned condition, not making a new redirect, creating a loop.

  • I ran the code edited by vc, but the error persists. Thanks for the attention.

  • Clear cache and cookies, or use anonymous window to see if the problem persists.

  • I tried that. Oh, gosh. The code was running good.

  • If remove (all) the header('location:principal.php'); the problem still persists? If yes, can be a cache, access using another device (your mobile). Apparently there is nothing to redirect, since there is no upload, except if there is SESSION, but this would only be done if you have already connected.

  • I could not access with another device, because the system is on the localhost. Well I did what you sent, delete all header('Location:main.php'); up to the linked page_sessao.php. I am able to access the main page.php, log in to the profile.php page and go back to the main page.php by the exit button. But this is returning the following news:

  • >Notice: Undefined variable: _SESSION in C: xampp htdocs sessao.php on line 16 >Notice: Undefined variable: _SESSION in C: xampp htdocs sessao conexao_sessao.php on line 17 >Warning: session_destroy(): Trying to Destroy uninitialized Session in C:xampp htdocs sessao conexao_sessao.php on line 40 >Notice: Undefined variable: _SESSION in C: xampp htdocs sessao.php on line 43 >Notice: Undefined variable: _SESSION in C: xampp htdocs sessao conexao_sessao.php on line 44

  • If I set the header('Location:main.php'); on the linked page_sessao.php the redirect error happens again.

  • Well, remember the code of the linked page_sessao.php q you made me replace? So I ran it now without the header('Location:main.php'); .

  • The problem in this case is that it will not redirect if the user enters profile.php without having logged in. Try giving a session_start() at the top of the file, before //Seleciona o banco de dados, for the $_SESSION to work.

  • I figured out the exact moment the problem happens, is when I type an email that is not present in the database.

  • Try to change the if(mysql_num_rows ($resultado)) for if(mysql_num_rows ($resultado) >= 1), that way if it doesn’t work at all it won’t save a SESSION.

  • Tidied up. But within the system there were errors like Warning: mysql_fetch_assoc() expects Parameter 1 to be Resource, Boolean Given in C: xampp htdocs sessao Mostrar generos primeiraguerramundial.php on line 5

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.