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 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?