php - session_start() 错误总是重定向到 login.php

标签 php mysql

登录 (login.php) 页面工作正常,但它重定向到 index.php 页面

login.php

<?php 
 ob_start();
 session_start();  ?>   

<html>
<head>
<meta charset="utf-8">
    <form method="post" action="login.php" >
        <div class="form-group" >
            <input type="text" class="form-control" name="user_name" >
        </div>
        <div class="form-group">
            <input type="password" class="form-control" name="user_pass" >
        </div>
        <input type="submit" name="login" value="Login" > 
    </form>
</body>
</html>

<?php
    include '../includes/connection.php'; /* connection query */
    if (isset($_POST['login'])) {
        $username = $_POST['user_name'];
        $userpass = $_POST['user_pass'];

        $admin_query = "select * from admin_login where user_name =  '$username' AND user_pass = '$userpass'";

        $run = mysql_query($admin_query);     
        $rows = mysql_num_rows($run);

        if ($rows == 1) {
            $_SESSION['login_user']=$username;
            header("location: index.php");
        } else {
            echo "<script>alert('User name of password is incorrect')</script>";
        }
    }
?>

在索引页面(index.php)中, session 出现错误并且始终重定向到login.php

index.php

<?php
    session_start();
    if(!isset($_SESSION['login_user'])){
    header('Location: login.php');
    }
    else
    {
    ?>
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
    <div class="row cms-admin-panel">
     <div class="col-md-12 "><h5> Welcome: <?php echo $_SESSION['login_user'] ?>  </h5> <a href="logout.php">logout</a>
    <h4 align="center">CMS Admin Panel</h4>
    </div>
    </div>
    </body>
    </html>
    <?php } ?>

注销页面工作正常,它重定向到 login.php 页面。

logout.php

<?php  
    session_start();
    session_destroy();
    header("location: login.php");
?>

最佳答案

移动session_start();之前<form> .

The session_start() function must be the very first thing in your document. Before any HTML tags.

Where exactly do I put a SESSION_START?

长答案:

由于 session 默认由 cookie 处理,

To use cookie-based sessions, session_start() must be called before outputing anything to the browser.

http://php.net/manual/en/function.session-start.php

关于php - session_start() 错误总是重定向到 login.php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37794244/

相关文章:

php - 如果未重定向,则重定向页面

php - 在 php 邮件 header 中的 from 字段中使用逗号的问题

php - 让 jQuery 自动完成与 PHP 源一起工作

javascript - 使用 highchart 来自 MySQL 的实时数据

php - 如何比较 Android 和 MySQL 中的变量值?

MySQL - 找到 NULL 时设置默认返回值的方法?

php - mysql 请求逻辑

PHP mysqli_fetch_array 如何转到下一行?

php - 流明 PHP : hidden password field in model not filled using Model->fill()

mysql - 我的带有游标的存储过程没有运行