成功登录后重定向不起作用

时间:2018-05-18 04:26:41

标签: php redirect

我已经使用PHP创建了一个登录表单但是我遇到了一个问题,即我的home.php在登录成功后没有显示其内容。正在显示错误处理,如同两个字段都是必需的,用户名/通行证不正确。但是,如果我输入正确的凭证,那么它就不会显示我的home.php。

的login.php

<?php

session_start();
include("connection.php"); //Establishing connection with our database

$error = ""; //Variable for storing our errors.
if(isset($_POST["submit"])) {
    if($_POST["username"]== '' || $_POST["password"]=='') {
        $error = "Both fields are required.";
    } else {
        // Define $username and $password
        $username=$_POST['username'];
        $password=$_POST['password'];

        //Check username and password from database
        $sql="SELECT * FROM users WHERE username='$username' and password='$password'";
        $result=mysqli_query($db,$sql);
        $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

        if(mysqli_num_rows($result) == 1) {
            $_SESSION['username'] = $login_user; // Initializing Session
            header("location: home.php"); // Redirecting To Other Page
        } else {
            $error = "Incorrect username or password.";
        }
    }
}

?>

home.php

<?php
    include("check.php"); 
?>

<!doctype html>
<html>
    <head>
    <meta charset="utf-8">
        <title>Home</title>
        <link rel="stylesheet" href="style.css" type="text/css" />
    </head>
    <body>
        <h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
        <br><br><br>
        <a href="logout.php" style="font-size:18px">Logout?</a>
    </body>
</html>

check.php

<?php
    include('connection.php');
    session_start();
    $user_check=$_SESSION['username'];

    $sql=mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");

    $row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
    $login_user=$row['username'];

    if(!isset($user_check)) {
        header("Location: index.php");
    }
?>

2 个答案:

答案 0 :(得分:1)

两个要点

<强>第一 您的代码将始终继续运行,并且不会因位置更改而停止。这意味着你应该使用

exit;

// or

die();

完成程序的运行。

<强>第二 在php中重定向你应该使用这样的东西:

/* Redirect to a different page in the current directory that was requested */
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$page  = 'home.php';
header("Location: http://$host$uri/$page");
exit;
?>

答案 1 :(得分:0)

您没有在$ _SESSION ['username']中添加任何值,因为$ login_user没有任何值。