1 登錄頁面:login.php
<?php //判斷一下是否有cookie if (isset($_COOKIE['user']) && $_COOKIE['user']==='admin') { echo '您已經登錄'; echo "<a href='logout.php'>注銷登錄</a>"; exit(); } //登錄邏輯 if (isset($_POST['submit'])) { //判斷用戶名和密碼是否正確 if ( isset($_POST['user']) && isset($_POST['pwd']) && $_POST['user']==='admin' && $_POST['pwd'] === 'admin') { //寫入cookie if (setcookie('user',$_POST['user'],time()+3600)) { //設置cookie成功 跳轉到首頁 header('Location:skip.php?url=index.php&info=000登錄成功'); } else { echo 'cookie設置失敗'; } } else { header('Location:skip.php?url=index.php&info=登錄失敗'); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄頁面</title> </head> <body> <form method="post" action="login.php"> 姓名:<input type="text" name="user"/> 密碼:<input type="password" name="pwd" /> <input type="submit" name="submit" value="登錄"> </form> </body> </html>
2 首頁 index.php
<?php if (isset($_COOKIE['user']) && $_COOKIE['user'] === 'admin') { echo "親愛的{$_COOKIE['user']}你好,歡迎回來"; echo "<br><a href='logout.php'>注銷登錄</a>"; } else { echo "<a href='login.php'>請登錄</a>"; }
3 跳轉中轉頁 skip.php
<?php //跳轉中轉頁 if (!isset($_GET['url']) || !isset($_GET['info'])) { exit('url 或 info 沒有收到'); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>橋頁</title> <meta http-equiv="refresh" content="3;url=<?php echo $_GET['url'] ?>"> </head> <body> <div style="text-align:center;font-size:20px;"><?php echo $_GET['info'] ?>,3秒后自動跳轉!</div> </body> </html>
4 注銷登錄 logout.php
<?php //如果cookie存在 我們進行刪除 if (isset($_COOKIE['user']) && $_COOKIE['user'] === 'admin') { //刪除cookie操作 if (setcookie('user',$_POST['user'],time()+3600)) { //跳轉到登錄頁 header('Location:login.php'); } else { echo '刪除失敗 請重試'; } }
