douan3414 2014-02-07 11:48
浏览 36
已采纳

带有数据会话的PHP重定向会破坏

I'm trying to have a formular with header("location").

And it workes just fine except one thing. When im trying to set the session that is holding the message it sets the session but when im trying to write it out, the problems starting..

Its like he go inside the if then delete the cookie, jumps out of the if and trys to get there again..

Here is my code:

if (isset($_SESSION['sess_error'])) { 
    echo '<div class="alert alert-danger">';
    foreach ($_SESSION['sess_error'] as $val) { 
        echo $val.'<br>'; 
    }
    unset($_SESSION['sess_error']);
}

if (empty($_POST['username'])) { $error[] = 'Du måste fylla i ett användarnamn...'; }    
if (empty($_POST['password'])) { $error[] = 'Du måste fylla i ett lösenord...'; }
elseif ($sql->num_rows == 0) { $error[] = 'Något fel uppstog, du kunde inte bli inloggad...'; }
if (count($error) > 0) { 
    $_SESSION['sess_error'] = $error;
}

Anyone got any idea why this is happening and what can I do to prevent it?

The whole script:

<?php
SESSION_START();
    if (isset($_POST['login'])) { 
            $error = null;
            $username = $_POST['username'];
            $password = $_POST['password'];
            $sql = $mysqli->query("SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1");
            if (empty($_POST['username'])) { $error[] = 'Du måste fylla i ett användarnamn...'; }
            if (empty($_POST['password'])) { $error[] = 'Du måste fylla i ett lösenord...'; }
            elseif ($sql->num_rows == 0) { $error[] = 'Något fel uppstog, du kunde inte bli inloggad...'; }
                if (count($error) > 0) { 
                    $_SESSION['sess_error'] = $error;
                }
                else { 
                    while ($r = $sql->fetch_array()) { 
                        $_SESSION['sess_username'] = $r['username']; 
                        $_SESSION['sess_userID'] = $r['userID'];
                        $_SESSION['sess_admin'] = $r['admin']; 
                        $_SESSION['sess_logg'] = 1;
                    }
                }
                header("Location: ./");
            }
?>
  • 写回答

2条回答 默认 最新

  • douken0530 2014-02-07 12:36
    关注

    I solved the whole problem, i just had to add an exit; after the header(""); and it worked just fine!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?