关键词搜索

源码搜索 ×
×

PHP笔记-用户登录例子

发布2021-12-31浏览1023次

详情内容

程序运行截图如下:

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

文件如下;

index.php

  1. <?php
  2. @session_start();
  3. if(!isset($_SESSION["user"])){
  4. header("location:../login.html");
  5. return;
  6. }
  7. echo "首页";
  8. print_r($_COOKIE);
  9. print_r($_SESSION);
  10. echo "<a href='./logout.php' />退出登录";
  11. ?>

 login.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>登录</title>
  6. </head>
  7. <body>
  8. <form method="post" action="./login.php">
  9. <label class="log-lab">用户名</label>
  10. <input name="userName" type="text" value="" />
  11. <label content="log-lab">密码</label>
  12. <input name="password" type="password" value="" />
  13. <input type="submit" value="登录">
  14. </form>
  15. </body>
  16. </html>

 login.php

  1. <?php
  2. $userName = trim($_POST["userName"]);
  3. $password = trim($_POST["password"]);
  4. if(empty($userName) || empty($password)){
  5. header("location:./login.html");
  6. return;
  7. }
  8. //user/123456
  9. $user = ["name" => "user", "password" => "123456"];
  10. if($user["name"] !== $userName){
  11. echo "用户名错误";
  12. header("location:./login.html");
  13. return;
  14. }
  15. if($user["password"] !== $password){
  16. echo "密码错误";
  17. header("location:./login.html");
  18. return;
  19. }
  20. @session_start(["cookie_httponly" => true]);
  21. $_SESSION["user"] = ["name" => $userName, "password" => $password];
  22. header("location:./index.php");
  23. ?>

logout.php

  1. <?php
  2. session_start();
  3. session_destroy();
  4. header("location:./login.html");
  5. ?>

要注意的地方:

①index.php中的print_r($_COOKIE)

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

②index.php中的@session_start()

  1. /**
  2. * Initialize session data
  3. * @link https://php.net/manual/en/function.session-start.php
  4. * @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.
  5. * 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>
  6. * @return bool This function returns true if a session was successfully started,
  7. * otherwise false.
  8. */
  9. function session_start ($options = []) {}

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

③index.php中的$_COOKIE

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

④index.php中的$_SESSION

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

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载