PHP笔记-用户登录例子

2021/12/31 9:07:20

本文主要是介绍PHP笔记-用户登录例子,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

程序运行截图如下:

输入用户名密码后,点击登录后:

文件如下;

index.php

<?php
    @session_start();
    if(!isset($_SESSION["user"])){

        header("location:../login.html");
        return;
    }

    echo "首页";
    print_r($_COOKIE);
    print_r($_SESSION);
    echo "<a href='./logout.php' />退出登录";
?>

 login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <form method="post" action="./login.php">
        <label class="log-lab">用户名</label>
        <input name="userName" type="text" value="" />
        <label content="log-lab">密码</label>
        <input name="password" type="password" value="" />
        <input type="submit" value="登录">
    </form>
</body>
</html>

 login.php

<?php
    $userName = trim($_POST["userName"]);
    $password = trim($_POST["password"]);
    if(empty($userName) || empty($password)){

        header("location:./login.html");
        return;
    }

    //user/123456
    $user = ["name" => "user", "password" => "123456"];
    if($user["name"] !== $userName){

        echo "用户名错误";
        header("location:./login.html");
        return;
    }

    if($user["password"] !== $password){

        echo "密码错误";
        header("location:./login.html");
        return;
    }

    @session_start(["cookie_httponly" => true]);
    $_SESSION["user"] = ["name" => $userName, "password" => $password];
    header("location:./index.php");
?>

logout.php

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

要注意的地方:

①index.php中的print_r($_COOKIE)

 从中可以知道,这个函数打印变量,并且打印出来的变量具有高可读性。

②index.php中的@session_start()

/**
 * Initialize session data
 * @link https://php.net/manual/en/function.session-start.php
 * @param array $options [optional] <p>If provided, this is an associative array of options that will override the currently set session configuration directives. The keys should not include the session. prefix.
 * In addition to the normal set of configuration directives, a read_and_close option may also be provided. If set to TRUE, this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won't be changed.</p>
 * @return bool This function returns true if a session was successfully started,
 * otherwise false.
 */
function session_start ($options = []) {}

从中可知功能为初始化session数据。

③index.php中的$_COOKIE

 全局的变量是一个Cookie数组,保存了HTTP的cookie,功能与快废弃的$HTTP_COOKIE_VARS数组一样。

④index.php中的$_SESSION

 同样也是个全局变量,是Session数组,和以前的$HTTP_SESSION_VARS数组一样。功能是获取当前的session。



这篇关于PHP笔记-用户登录例子的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程