批改状态:合格
老师批语:每一种会话技术,都有优缺点, 现代会话控制技术是基于它们实现的
0714作业
设置cookie的方式:
setcookie()设置cookie
setcookie(‘name’,’value’,’expire’,’path’,’domain’,’secure’,’httponly’);
<?php// 示例:setcookie设置一个cookie,第三个参数设置过期setcookie("user","emagic",time()+60);print_r($_COOKIE);
<?php// 示例:header()设置一个cookieheader('Set-cookie:username = Emagictest');print_r($_COOKIE);
<?php// 1:查看单个echo $_COOKIE['user'],'<hr>';// 2:查看所有print_r($_COOKIE);
<?php// 删除cookie方法1setcookie("username","");print_r($_COOKIE);// 删除cookie方法2setcookie("username","",time()-1);print_r($_COOKIE);
cookie设置后再第二次加载时才能显示出来的原因:第一次在响应头中存在,第二次在请求头中显示,因为第一次请求时候浏览器本地还没有cookie,是通过后端php代码设置才响应从在响应头中返回,第二次本地如果没过期已经有了就附带在请求头中发送会话
<?phpsession_start();// $_SESSION通过超全局变量设置$_SESSION["user"] = "admintest";// 查看指定session值 $_SESSION['名称'];print_r($_SESSION['user']);echo "<hr>";// 查看全部session值print_r($_SESSION);


<?phpsession_start();//清空全局变量unset($_SESSION['user']);// session_destroy(); 销毁所有session,包括后台文件也删掉,没有参数// session_destroy();print_r($_SESSION);
login.php
<?php// 登录页面// 获取post提交的值$username = $_POST['username'];$password = $_POST['password'];// echo $username,$password;// 自定义一个函数用于清除cookie中所有的用户信息function clearCookies(){setcookie("username","",0);setcookie("status","",0);}// 判断是否提交数据if (isset($_POST['submit'])) {// 判断用户名和密码是否正确if ($username == 'admintest' && $password=='123456') {// 调用自定义函数清除之前的登录用户cookieclearCookies();// 信息正确才设置cookiesetcookie('username',$username,strtotime(" +7 days"));// 设置status登陆状态setrawcookie('status','1',strtotime(" +7 days"));// 设置完成直接跳转页面header("Location:index.php");} else {exit('用户名或密码不正确');}}// 当点击退出时跳转到该页面并在get中附带action动作,值等于logoutif ($_GET['action'] == "logout") {clearCookies();}?><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><form style="border:solid;width:300px;height:250px;padding:20px;" action="" method="POST"><h2>用户登录</h2><div><label for="username">用户名</label><input type="text" name="username" id="username" placeholder="请输入登录名" required="required"></div><div><label for="password">密  码</label><input type="password" name="password" id="password" placeholder="请输入密码" required="required"></div><input type="submit" name="submit" value="提交"></form></body></html>
index.php
<?php?><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><h1>登陆成功:</h1><?php echo $_COOKIE['username']?><a href="login.php?action=logout">退出登录</a></body></html>

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号