Php 在同一页面中包含会话变量的登录表单

Php 在同一页面中包含会话变量的登录表单,php,session,login,session-variables,Php,Session,Login,Session Variables,我正在尝试运行我的小测试脚本,一个使用PHP的登录面板 我希望index.php有一个任何人都可以查看的公共部分,但是当用户登录时,应该会看到公共页面以及基于数据会话从数据库获得的其他数据(例如,用户名) 为了更好地理解一切,我将附上一张我希望它如何运行我的脚本的图片(示例): 我的代码如下: index.php <!DOCTYPE html> <html lang="es"> <head> <title>PHP - Lo

我正在尝试运行我的小测试脚本,一个使用PHP的登录面板

我希望index.php有一个任何人都可以查看的公共部分,但是当用户登录时,应该会看到公共页面以及基于数据会话从数据库获得的其他数据(例如,用户名)

为了更好地理解一切,我将附上一张我希望它如何运行我的脚本的图片(示例):

我的代码如下:

index.php

<!DOCTYPE html>
<html lang="es">
    <head>
        <title>PHP - Log in - test page</title>
        <style>
            .container{text-align:justify;width:300px;}
            span{font-size:22px;}

        </style>
    </head>
    <body>
    <div class="info">
        <h1>PHP TEST PAGE</h1>
<?php
    if ($login_session == null)
    {
        echo "<span><a href='loginpanel.php'>Log in</a></span>";
    }
    else
    {
        echo "<span>{$login_session}</span>";
        echo "<span><a href='loginpanel.php'>Log out</a></span>";
    }
?>
    <div class="container">
        <p>
            Lorem ipsum dolor sit amet, usu ei mazim exerci everti, quas numquam interesset sed te. Dicunt epicurei moderatius sed at. Integre detraxit quaerendum ut has. Sea ut viderer sensibus.
        </p>
        <p>
            Sed ad idque detraxit probatus, ne feugiat mediocrem eos. Quo an veniam iisque, ignota integre elaboraret vix ut. Et mea ludus aliquid legimus, nam te illud atqui cetero. Tempor feugiat delicatissimi pro ad.
        </p>
    </div>
</body>
<?php
    require_once('login.php');
    $error = isset($_GET['error']) ? $_GET['error'] : NULL; 
?>
<!DOCTYPE html>
<html lang="es">
    <head>
        <title>Log in panel</title>
    </head>
    <body>
        <form action="" method="POST">
            <input maxlength='64' name="username" type="user" placeholder="User" required>
            <input maxlength='64' name="password" type="password" placeholder="Pass" required>
            <button type="submit" name="submit">LOG IN</button>
        </form>
        <h4 style="color:crimson;"><?php if ($error == 1){echo "Wrong user or pass";} ?></h4>
    </body>
</html>
<?php
    $connection = new mysqli("127.0.0.1","root","myultrasecureandsecretpassword","mydatabase");
    if (mysqli_connect_errno())
    {
        echo "ERROR; THE APOCALYPSIS IS NEAR!: " . mysqli_connect_error();
    }
?> 
<?php
    require_once('conexion.php');
    session_start();//starting session
    $error=''; //variable to store error message
    if (isset($_POST['submit']))
    {
        if (empty($_POST['username']) || empty($_POST['password']))
        {
            $error = "user or pass wrong"; 
        }
        else 
        {
            // Define $username and $password 
            $username=$_POST['username']; 
            $password=$_POST['password']; 

            // To protect MySQL injection for Security purpose 
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($connection, $username);
            $password = mysqli_real_escape_string($connection, $password);

            //SQL query to fetch information of registerd users and finds user match.
            $query=$connection->query("SELECT usuario
                                FROM usuarios
                                WHERE usuario='{$username}' 
                                AND password='{$password}'
                                ");
            $fila=$query->fetch_row();
            $rows = mysqli_num_rows($query);
            if ($rows == 1)
            {
                $_SESSION['login_user']=$username;//Initializing Session
                header("Location: index.php");//Redirecting to other page
            }
            else 
            {
                header("Location: loginpanel.php?error=1");//Redirecting to other page
            }
            //Closing Connection
            mysqli_close($connection);
        }
    }
?>
<?php
    require_once('conexion.php');
    session_start();// Starting Session
    //Storing session
    $user_check=$_SESSION['login_user'];

    //SQL query to fetch complete information of user
    $ses_sql = $connection->query("SELECT usuario FROM usuarios WHERE usuario='{$user_check}'");
    $row = $ses_sql->fetch_assoc();

    $login_session=$row['usuario'];
    if(!isset($login_session))
    {
        //Closing Connection
        mysqli_close($connection);
        header('Location: index.php');//Redirecting to home page 
    }
?>
<?php
    session_start();
    if(session_destroy()) //Destroying all sessions
    {
        header("Location: index.php"); //Redirecting to home page
    }
?>

PHP-登录-测试页面
.container{文本对齐:对齐;宽度:300px;}
span{font size:22px;}
PHP测试页

同一天的同一天的同一天,通常是每一天的同一天的同一天,也可能是同一天的同一天。伊壁鸠鲁对我们说。整数detraxit quaerendum ut具有。海是一种感觉。

这是一个封建的平庸之辈。这是一个威尼斯式的整体。这是一个不公平的法律,不公平。临时封建主义。

loginpanel.php

<!DOCTYPE html>
<html lang="es">
    <head>
        <title>PHP - Log in - test page</title>
        <style>
            .container{text-align:justify;width:300px;}
            span{font-size:22px;}

        </style>
    </head>
    <body>
    <div class="info">
        <h1>PHP TEST PAGE</h1>
<?php
    if ($login_session == null)
    {
        echo "<span><a href='loginpanel.php'>Log in</a></span>";
    }
    else
    {
        echo "<span>{$login_session}</span>";
        echo "<span><a href='loginpanel.php'>Log out</a></span>";
    }
?>
    <div class="container">
        <p>
            Lorem ipsum dolor sit amet, usu ei mazim exerci everti, quas numquam interesset sed te. Dicunt epicurei moderatius sed at. Integre detraxit quaerendum ut has. Sea ut viderer sensibus.
        </p>
        <p>
            Sed ad idque detraxit probatus, ne feugiat mediocrem eos. Quo an veniam iisque, ignota integre elaboraret vix ut. Et mea ludus aliquid legimus, nam te illud atqui cetero. Tempor feugiat delicatissimi pro ad.
        </p>
    </div>
</body>
<?php
    require_once('login.php');
    $error = isset($_GET['error']) ? $_GET['error'] : NULL; 
?>
<!DOCTYPE html>
<html lang="es">
    <head>
        <title>Log in panel</title>
    </head>
    <body>
        <form action="" method="POST">
            <input maxlength='64' name="username" type="user" placeholder="User" required>
            <input maxlength='64' name="password" type="password" placeholder="Pass" required>
            <button type="submit" name="submit">LOG IN</button>
        </form>
        <h4 style="color:crimson;"><?php if ($error == 1){echo "Wrong user or pass";} ?></h4>
    </body>
</html>
<?php
    $connection = new mysqli("127.0.0.1","root","myultrasecureandsecretpassword","mydatabase");
    if (mysqli_connect_errno())
    {
        echo "ERROR; THE APOCALYPSIS IS NEAR!: " . mysqli_connect_error();
    }
?> 
<?php
    require_once('conexion.php');
    session_start();//starting session
    $error=''; //variable to store error message
    if (isset($_POST['submit']))
    {
        if (empty($_POST['username']) || empty($_POST['password']))
        {
            $error = "user or pass wrong"; 
        }
        else 
        {
            // Define $username and $password 
            $username=$_POST['username']; 
            $password=$_POST['password']; 

            // To protect MySQL injection for Security purpose 
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($connection, $username);
            $password = mysqli_real_escape_string($connection, $password);

            //SQL query to fetch information of registerd users and finds user match.
            $query=$connection->query("SELECT usuario
                                FROM usuarios
                                WHERE usuario='{$username}' 
                                AND password='{$password}'
                                ");
            $fila=$query->fetch_row();
            $rows = mysqli_num_rows($query);
            if ($rows == 1)
            {
                $_SESSION['login_user']=$username;//Initializing Session
                header("Location: index.php");//Redirecting to other page
            }
            else 
            {
                header("Location: loginpanel.php?error=1");//Redirecting to other page
            }
            //Closing Connection
            mysqli_close($connection);
        }
    }
?>
<?php
    require_once('conexion.php');
    session_start();// Starting Session
    //Storing session
    $user_check=$_SESSION['login_user'];

    //SQL query to fetch complete information of user
    $ses_sql = $connection->query("SELECT usuario FROM usuarios WHERE usuario='{$user_check}'");
    $row = $ses_sql->fetch_assoc();

    $login_session=$row['usuario'];
    if(!isset($login_session))
    {
        //Closing Connection
        mysqli_close($connection);
        header('Location: index.php');//Redirecting to home page 
    }
?>
<?php
    session_start();
    if(session_destroy()) //Destroying all sessions
    {
        header("Location: index.php"); //Redirecting to home page
    }
?>

登录面板
登录
conexion.php

<!DOCTYPE html>
<html lang="es">
    <head>
        <title>PHP - Log in - test page</title>
        <style>
            .container{text-align:justify;width:300px;}
            span{font-size:22px;}

        </style>
    </head>
    <body>
    <div class="info">
        <h1>PHP TEST PAGE</h1>
<?php
    if ($login_session == null)
    {
        echo "<span><a href='loginpanel.php'>Log in</a></span>";
    }
    else
    {
        echo "<span>{$login_session}</span>";
        echo "<span><a href='loginpanel.php'>Log out</a></span>";
    }
?>
    <div class="container">
        <p>
            Lorem ipsum dolor sit amet, usu ei mazim exerci everti, quas numquam interesset sed te. Dicunt epicurei moderatius sed at. Integre detraxit quaerendum ut has. Sea ut viderer sensibus.
        </p>
        <p>
            Sed ad idque detraxit probatus, ne feugiat mediocrem eos. Quo an veniam iisque, ignota integre elaboraret vix ut. Et mea ludus aliquid legimus, nam te illud atqui cetero. Tempor feugiat delicatissimi pro ad.
        </p>
    </div>
</body>
<?php
    require_once('login.php');
    $error = isset($_GET['error']) ? $_GET['error'] : NULL; 
?>
<!DOCTYPE html>
<html lang="es">
    <head>
        <title>Log in panel</title>
    </head>
    <body>
        <form action="" method="POST">
            <input maxlength='64' name="username" type="user" placeholder="User" required>
            <input maxlength='64' name="password" type="password" placeholder="Pass" required>
            <button type="submit" name="submit">LOG IN</button>
        </form>
        <h4 style="color:crimson;"><?php if ($error == 1){echo "Wrong user or pass";} ?></h4>
    </body>
</html>
<?php
    $connection = new mysqli("127.0.0.1","root","myultrasecureandsecretpassword","mydatabase");
    if (mysqli_connect_errno())
    {
        echo "ERROR; THE APOCALYPSIS IS NEAR!: " . mysqli_connect_error();
    }
?> 
<?php
    require_once('conexion.php');
    session_start();//starting session
    $error=''; //variable to store error message
    if (isset($_POST['submit']))
    {
        if (empty($_POST['username']) || empty($_POST['password']))
        {
            $error = "user or pass wrong"; 
        }
        else 
        {
            // Define $username and $password 
            $username=$_POST['username']; 
            $password=$_POST['password']; 

            // To protect MySQL injection for Security purpose 
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($connection, $username);
            $password = mysqli_real_escape_string($connection, $password);

            //SQL query to fetch information of registerd users and finds user match.
            $query=$connection->query("SELECT usuario
                                FROM usuarios
                                WHERE usuario='{$username}' 
                                AND password='{$password}'
                                ");
            $fila=$query->fetch_row();
            $rows = mysqli_num_rows($query);
            if ($rows == 1)
            {
                $_SESSION['login_user']=$username;//Initializing Session
                header("Location: index.php");//Redirecting to other page
            }
            else 
            {
                header("Location: loginpanel.php?error=1");//Redirecting to other page
            }
            //Closing Connection
            mysqli_close($connection);
        }
    }
?>
<?php
    require_once('conexion.php');
    session_start();// Starting Session
    //Storing session
    $user_check=$_SESSION['login_user'];

    //SQL query to fetch complete information of user
    $ses_sql = $connection->query("SELECT usuario FROM usuarios WHERE usuario='{$user_check}'");
    $row = $ses_sql->fetch_assoc();

    $login_session=$row['usuario'];
    if(!isset($login_session))
    {
        //Closing Connection
        mysqli_close($connection);
        header('Location: index.php');//Redirecting to home page 
    }
?>
<?php
    session_start();
    if(session_destroy()) //Destroying all sessions
    {
        header("Location: index.php"); //Redirecting to home page
    }
?>

login.php

<!DOCTYPE html>
<html lang="es">
    <head>
        <title>PHP - Log in - test page</title>
        <style>
            .container{text-align:justify;width:300px;}
            span{font-size:22px;}

        </style>
    </head>
    <body>
    <div class="info">
        <h1>PHP TEST PAGE</h1>
<?php
    if ($login_session == null)
    {
        echo "<span><a href='loginpanel.php'>Log in</a></span>";
    }
    else
    {
        echo "<span>{$login_session}</span>";
        echo "<span><a href='loginpanel.php'>Log out</a></span>";
    }
?>
    <div class="container">
        <p>
            Lorem ipsum dolor sit amet, usu ei mazim exerci everti, quas numquam interesset sed te. Dicunt epicurei moderatius sed at. Integre detraxit quaerendum ut has. Sea ut viderer sensibus.
        </p>
        <p>
            Sed ad idque detraxit probatus, ne feugiat mediocrem eos. Quo an veniam iisque, ignota integre elaboraret vix ut. Et mea ludus aliquid legimus, nam te illud atqui cetero. Tempor feugiat delicatissimi pro ad.
        </p>
    </div>
</body>
<?php
    require_once('login.php');
    $error = isset($_GET['error']) ? $_GET['error'] : NULL; 
?>
<!DOCTYPE html>
<html lang="es">
    <head>
        <title>Log in panel</title>
    </head>
    <body>
        <form action="" method="POST">
            <input maxlength='64' name="username" type="user" placeholder="User" required>
            <input maxlength='64' name="password" type="password" placeholder="Pass" required>
            <button type="submit" name="submit">LOG IN</button>
        </form>
        <h4 style="color:crimson;"><?php if ($error == 1){echo "Wrong user or pass";} ?></h4>
    </body>
</html>
<?php
    $connection = new mysqli("127.0.0.1","root","myultrasecureandsecretpassword","mydatabase");
    if (mysqli_connect_errno())
    {
        echo "ERROR; THE APOCALYPSIS IS NEAR!: " . mysqli_connect_error();
    }
?> 
<?php
    require_once('conexion.php');
    session_start();//starting session
    $error=''; //variable to store error message
    if (isset($_POST['submit']))
    {
        if (empty($_POST['username']) || empty($_POST['password']))
        {
            $error = "user or pass wrong"; 
        }
        else 
        {
            // Define $username and $password 
            $username=$_POST['username']; 
            $password=$_POST['password']; 

            // To protect MySQL injection for Security purpose 
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($connection, $username);
            $password = mysqli_real_escape_string($connection, $password);

            //SQL query to fetch information of registerd users and finds user match.
            $query=$connection->query("SELECT usuario
                                FROM usuarios
                                WHERE usuario='{$username}' 
                                AND password='{$password}'
                                ");
            $fila=$query->fetch_row();
            $rows = mysqli_num_rows($query);
            if ($rows == 1)
            {
                $_SESSION['login_user']=$username;//Initializing Session
                header("Location: index.php");//Redirecting to other page
            }
            else 
            {
                header("Location: loginpanel.php?error=1");//Redirecting to other page
            }
            //Closing Connection
            mysqli_close($connection);
        }
    }
?>
<?php
    require_once('conexion.php');
    session_start();// Starting Session
    //Storing session
    $user_check=$_SESSION['login_user'];

    //SQL query to fetch complete information of user
    $ses_sql = $connection->query("SELECT usuario FROM usuarios WHERE usuario='{$user_check}'");
    $row = $ses_sql->fetch_assoc();

    $login_session=$row['usuario'];
    if(!isset($login_session))
    {
        //Closing Connection
        mysqli_close($connection);
        header('Location: index.php');//Redirecting to home page 
    }
?>
<?php
    session_start();
    if(session_destroy()) //Destroying all sessions
    {
        header("Location: index.php"); //Redirecting to home page
    }
?>

注意:未定义变量:第15行C:\xampp\htdocs\testlogin\index.php中的login\u会话

好的,那么看一下
index.php
的第15行:

if ($login_session == null)
这是该文件中的第一行PHP代码。没有任何地方真正定义了
$login\u session
。所以即使没有通知,它也永远不会有价值

变量在脚本执行之间不保持其值。每次执行脚本时,它都从零开始。如果要在执行之外保留值,则需要将其保留在某个位置。根据变量的名称判断,您可能希望使用

您可能会使用以下内容检查值:

if (isset($_SESSION['login']))
$_SESSION['login'] = $row['usuario'];
(可能还需要对值本身进行第二次检查,而不仅仅是检查它是否存在)

你可以这样写:

if (isset($_SESSION['login']))
$_SESSION['login'] = $row['usuario'];

从一页到下一页,代码不保留变量的内存。值需要被一个页面保存在某个地方,以便被另一个页面读取。

在本例中,a
require(“session.php”)应该已经完成了操作。@EricBouwers在第一次尝试中工作得很好,但在执行F5时出现了以下错误:“页面重定向不正确Firefox检测到服务器正在以一种永远无法完成的方式重定向对此地址的请求。此问题可能由以下原因引起:有时禁用或拒绝接受Cookie。“@candlejack:嗯,当
session.php
包含以下行时,在
index.php
中包含
session.php
有点危险:
header('Location:index.php'))
。最好将公共逻辑与响应逻辑分开,这样的重定向就是响应逻辑。理想情况下,它应该是页面级别,而不是公共文件级别。我明白了,但不可能实现我想要的功能?我想要索引公共部分(不需要登录),但我也希望当用户登录时,用户名出现。@candlejack:完全可以做你想做的事。只需检查
$\u SESSION
值,而不是使用未初始化的变量。这有点傲慢,很遗憾像StackOverflow这样的网站有用户发表这样的评论。另一方面,幸运的是,我们拥有如果你是真正的专业人士,比如@David和EricBouwersHonestly,你花了多少时间来检查你的代码中缺少的变量声明?不要把“傲慢”声明强加给我或其他任何人。如果你愿意告诉我们/我:“我花了大约一个小时在这个问题上,但是我仍然不明白为什么我的代码在我身上失败了。你们能告诉我哪里出了问题吗?“而不仅仅是一个简单的“我该怎么做?”你们给我们扔下了堆积如山的代码,你们期待什么?