PHP笔记-用户登录例子
生活随笔
收集整理的這篇文章主要介紹了
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
<?phpsession_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笔记-用户登录例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Web前端笔记-two.js实现坐标定位
- 下一篇: php返回200,关于API 使用 HT