Incorrect redirection

Asked

Viewed 1,327 times

0

I am trying to redirect registered users to the control panel and other visitors to the login page, but I get this message:

inserir a descrição da imagem aqui

Login

<?php
$page = "Login";
include "header.php";

$user_error='';
$pass_error='';

if(isset($_POST["login"])){

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

if(empty($username)){
    $user_error = 'Please insert a username';
}
elseif(!empty($username)){
    $checkusername = mysql_query("SELECT * FROM `database`.`user` WHERE `username` = '".$username."'");
    if(mysql_num_rows($checkusername) == 0){
        $user_error = 'Wrong username';
    }
}
if(empty($password)){
    $pass_error = 'Please insert a password';
}
elseif(!empty($password)){
    $checkpassword = mysql_query("SELECT * FROM `database`.`user` WHERE `username` = '".$username."' AND `password` = '".$password."'");
    if(mysql_num_rows($checkpassword) == 0){
        $pass_error = 'Wrong password';
    }
}
}
if(empty($user_error)&& empty($pass_error)&& isset($_POST['login'])){

$login_check = mysql_query("SELECT * FROM `database`.`user` WHERE `username` = '".$username."' and password = '".$password."'") or die(mysql_error());

if(mysql_num_rows($login_check) == 1){

    setcookie("username",$username);
    $_SESSION['username'];
    $_SESSION['password'];
    header("Location: control-painel.php");
    $logged == 1;
}
 }
     else{
    $user_error = empty($user_error)?'' : htmlEntities($user_error);
    $pass_error = empty($pass_error)?'' : htmlEntities($pass_error);
 ?>

<div id="loginform">
    <form name="loginform" method="post">
        <table cellpadding="0" id="tb">
            <tr>
            <td colspan="2">
            <div class="loginheader">
            <h2>Login</h2>
            </div>
            </td>
            </tr>
        </table>
            <div id="message">
                <?php echo $user_error; ?><br><br>
                <?php echo $pass_error; ?>
            </div>
        <table cellpadding="0">
            <tr>
            <td class="field">Username:</td>
            <td><input type="text" class="text" name="username"></td>
            </tr>
            <tr>
            <td class="field">Password:</td>
            <td><input type="password" class="text" name="password"></td>
            </tr>
        </table>
        <table cellpadding="0">
            <tr>
            <td class="field"></td>
            <td><input type="submit" class="submitbutton" name="login" value="Login"/></td>
            </tr>
        </table>
    </form>
</div>

<?php
}
include "footer.php";
?>

Logout

<?php
if(isset($_POST['logout'])){
session_start();
session_destroy();
header("Location: index.php");
}
?>

Control Panel

<?php
$page = "Control Painel";
include "header.php";

if(!isset($_SESSION['username'], $_SESSION['password'], $logged)){
header("location: control-painel.php");
}
else{
header("location: login.php");
}
?>

<form action="logout.php" method="post">
<input type="submit" class="submitbutton" name="logout" value="Logout"/>
</form>

<?php
include "footer.php";
?>
  • You already have an answer on this link: http://answall.com/questions/13386/login-em-php-niveis-de-permissao?rq=1

  • Use sessions and encrypt data. Read the session manual.

  • Where do I find this manual?

1 answer

2


You need to review your logic a little better.

  1. There are redundant queries on the login page.
  2. You don’t need to separate login validation from password validation, even for security reasons (you don’t want a malicious user to discover a valid login in the right application?).
  3. You can also use Try/catch to better organize the code.
  4. The error reported is occurring because the page control panel redirects to itself if there is no session. Then there will be no session again and it will redirect to itself. This will stay in an eternal loop.

Follow my suggestion:

login.php

$error = '';
if (isset($_REQUEST['login']))
{
    try
    {
        if (empty($_REQUEST['username']))
            throw new Exception('Informe o seu login.');     

        if (empty($_REQUEST['password']))
            throw new Exception('Informe a senha.');     

        $username = mysql_real_escape_string($_REQUEST['username']);
        $password = mysql_real_escape_string($_REQUEST['password']);
        $result = mysql_query("SELECT * FROM `database`.`user` WHERE `username` = '".$username."' AND `password` = '".$password."'");

        if ($row = mysql_fetch_array($result))
        {
             session_start();
             $_SESSION['id'] = $row['id'];
             // Acrescente à sessão outras informações que desejar, mas
             // normalmente o id é a informação principal.

             header('location: control-painel.php');
        }
        else throw new Exception('Login/senha inválidos.');    
    }
    catch (Exception $e)
    {
         $error = $e->getMessage();
    }
}

// A variável $error possuirá o erro (se houver).
// Pra saber se houve erro basta verificar if (!empty($error)){}.

control-session.php

session_start();
if (!isset($_SESSION['id']))
    header('location: login.php');

On every page you want to control access (only logged in users can access) include the file 'control-session.php':

control-panel.php

// Isso precisa estar antes de qualquer conteúdo HTML.
// Recomendo que seja o primeiro comando da página.
require_once 'controle-sessao.php'

logout.php

session_start();
session_destroy();
header('location: login.php');
  • The past code is just a guideline. I haven’t tested it. Understand the logic and apply it to your project!

Browser other questions tagged

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