dscuu86620 2017-03-24 07:59
浏览 37
已采纳

在PHP上使用Session

I'm new to PHP programming, I have code for user Login, and already connected to localhost database.

Here is the Login.php code

<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <div>
        <form action="doLogin.php" method="POST">
            <p>
                <label>Username : </label>
                <input type="text" id="username" name="user">
            </p>
            <p>
                <label>Password : </label>
                <input type="text" id="password" name="pass">
            </p>
            <p>
                <input type="submit" id="btnLogin" value="Login">
            </p>
        </form>
    </div>
</body>
</html>

and doLogin.php

<?php
    $username = $_POST["user"];
    $password = $_POST["pass"];

    $username = stripcslashes($username);
    $password = stripcslashes($password);

    $con = mysqli_connect('localhost', 'root', '', 'dbtest');

    $query = mysqli_query($con, "select * from user where Username = '$username' and Password = '$password' ");
    $row = mysqli_fetch_array($query);

    if ($row['Username'] == $username && $row['Password'] == $password)
    {
        echo "You are Success Login!!! Welcome ".$row['Username'];
        header('Location: Profile.php');
    }
    else
    {
        echo "Failed to login!";
    }
?>

I want to using session so if the user not logged in, it will redirect to Login page. Where and how I apply a session into my code, much appreciate it.

  • 写回答

3条回答 默认 最新

  • doukuipei9938 2017-04-05 04:04
    关注

    I've done some searching and I implement this code.

    I create session.php file, here is the code

    <?php
        function checkSession()
        {
            if(!isset($_SESSION))
            {
                session_start();
            }
            $username=$_SESSION['Username'];
            if(empty($username))
            {
                return true;
            }
            return false;
        }
    ?>
    

    And I place this code for every page that I protect from unauthorized user on top of the code.

    <?php
        require_once("session.php");
        if(checkSession())
        {
            header('Location: Login.php');
            exit;
        }
        else
        {
    ?>
            //User Logged in...
    <?php
        }
    ?>
    

    Hope this could help others new to PHP programming that had the same problem.

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大