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 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?