Session
这次只举例子,从例子中学习。直接上代码,建议不要粘贴复制,用手完全照着敲出来,增强印象。(没有用到数据库)
1. 4.12.php开启会话 session_start() ;
1 <?php 2 /* 3 * 4 * @Authors peng--jun 5 * @Email 1098325951@qq.com 6 * @Date 2015-11-04 13:00:16 7 * @Link http://www.cnblogs.com/xs-yqz/ 8 * @version $Id$ 9 ========================================== 10 */ 11 12 session_start(); 13 header("Content-type: text/html; charset=UTF-8"); 14 $_SESSION["username"]="彭军"; 15 $_SESSION["username"]="彭军军";//修改Session变量值 16 $_SESSION["age"] = 21; 17 $email = "1098325951@qq.com"; 18 $_SESSION["email"] = $email;//将变量信息存储到Session中 19 $_SESSION["user"] = array('name' =>"peng-jun" ,'pwd' => "123" ); //将数组存入Session 中 20 ?>
2. 4.13.php将session里面的值显示出来
1 header("Content-type: text/html; charset=UTF-8"); 2 session_start(); 3 echo $_SESSION["username"]; 4 echo $_SESSION["age"]; 5 echo $_SESSION["email"]; 6 echo $_SESSION["user"];
3. 以下4.14.php通过一个表单的例子(admin ,123)来验证会话
1 <?php 2 /* 3 * 4 * @Authors peng--jun 5 * @Email 1098325951@qq.com 6 * @Date 2015-11-04 13:16:06 7 * @Link http://www.cnblogs.com/xs-yqz/ 8 * @version $Id$ 9 ========================================== 10 */ 11 header("Content-type: text/html; charset=UTF-8"); 12 session_start(); 13 if (isset($_POST["submit"])) { 14 $user = $_POST["username"]; 15 $pw = $_POST["pwd"]; 16 if ($user == "admin" && $pw == "123") { 17 $_SESSION["user"] = $user;//通过这样来传递session参数 18 header('Location:4.15.php');//header的location进行页面的跳转 19 }else{ 20 echo "用户名或密码错误"; 21 } 22 }else{ 23 echo ' 24 <form method ="post" action=""> 25 用户名:<input type="text" name="username" /> 26 密 码:<input type ="password" name="pwd"/> 27 <input name="submit" type="submit" value="登录"/> 28 </form> 29 '; 30 } 31 ?>
4 4.15.php验证通过的页面
header("Content-type: text/html; charset=UTF-8"); session_start(); if (isset($_SESSION['user'])) { echo "欢迎你,".$_SESSION['user']."<br/> <a href = '4.16.php?action=logout'>注销登录</a>"; }else{ echo "未登录用户禁止访问"; }
5 用户注销的页面代码4.16.php
1 if ($_GET["action"] == "logout") { 2 session_start();//启动会话 3 setcookie("user","",time()-60);//将会话Cookie变量user设置为过期,即删除Cookie 4 session_unset();//删除$_SESSION中的Session变量 5 session_destroy();//销毁Session,删除Session ID 6 header("location:4.14.php"); //回到登陆页面 7 }