批改状态:合格
老师批语:可以
$_SESSION['school']='pdu';//方法1,先判断后删除if(isset($_SESSION['school'])){unset($_SESSION['school']);}//方法2,直接删除unset($_SESSION['school']);
$_SESSION['name']='zhangsan';session_destroy();print_r($_SESSION); //只是销毁了保留用户信息的Session文件,但没有清空Session这个超全局数组中的内容。还可以打印出来内容
//使用 $_SESSION = array() 清空 $_SESSION 数组的同时,也将这个用户在服务器端对应的 Session 文件内容清空,但不删除文件$_SESSION=[];print_r($_SESSION);
彻底删除session的话,要结合session_destroy()和设置设置session超全局数组为空。
两个文件:
login.php登陆页面
index.php登陆成功显示的页面
login.php代码如下:
<?php//判断是否处理登陆状态,如果是直接跳转到index.phpif((isset($_COOKIE["isLogin"]) && $_COOKIE["isLogin"]=="1")){header("Location:index.php");}$username=$_POST["username"];$password=$_POST["password"];function clearCookie(){setcookie("username","",time()-3600);setcookie("password","",time()-3600);}if($_POST["submit"]){ if($username=="xiaoming"&&$password=="123456"){clearCookie();setcookie("isLogin",1,time()+3600*24*7);//设置cookies日期为一周setcookie("username",$username,time()+3600*24*7);setcookie("password",$password,time()+3600*24*7);header("Location:index.php");}else{exit("用户名或者密码错误!");}}?><form action="" method="post"><label>用户名:<input type="text" name="username" placeholder="请输入用户名"></label><label>密码:<input type="text" name="password" placeholder="请输入密码"></label><input type="submit" name="submit"></form>
index.php页面代码如下
<?phpif(!(isset($_COOKIE["isLogin"]) && $_COOKIE["isLogin"]=="1")){exit( "<script>alert(\"您还没有登陆,请登陆!\");location.href=\"login.php\"</script>");}if ($_GET["action"]=="logout"){setcookie("username","",time()-3600);setcookie("password","",time()-3600);header("Location:login.php");}?>欢迎您,<?php echo $_COOKIE["username"] ?> <a href="?action=logout">退出</a>
效果如下:
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号