会话控制——session

一、session的作用与cookie的作用相似,但是最大的不同在于session是将数据存放于服务器中。另外,session的应用必须先启动(session_start()函数)。

  所以,在客户端仅需保存客户的sessionID,而在服务器端(文件、数据库、memcache)中保存session变量的值。

  默认处理方式是使用web服务器中的的文件来记录每个用户的会话信息。

  用户请求web服务器时,将sessionID的值发送给服务器,在通过sessionID取出session变量。

二、一个简单的邮件系统实例

  1.connect.inc.php

<?php 

    define("DSN", "mysql:host=localhost;dbname=testmail");
    define("DBUSER","root");
    define("DBPASS","root");
    try{
        $pdo = new PDO(DSN,DBUSER,DBPASS);
    }catch($PDOException $e)
    {
        die("连接失败:".$e->getMessage());
    }
?>

  2.login.php 

 1 <?php 
 2 
 3     session_start();
 4     require "connect.inc.php";
 5     if(isset($_POST['sub']))
 6     {
 7         $stmt = $pdo -> prepare("select id,username from user where username=? and userpass=?");
 8         $stmt -> execute(arrary($_POST["username"],$_POST["password"]));
 9         if($stmt -> rowCount()>0)
10         {
11             $_SESSION = $stmt -> fetch(PDO:FETCH_ASSOC);//将用户全部信息注册到session
12             $_SESSION["isLogin"] = 1;
13             header("Localtion:index.php");
14         }
15         else
16         {
17             echo "用户名或者密码错误";
18         }
19     }
20 ?>
21 <html>
22 <head><title>邮件登录系统</title></head>
23 <body>
24     <p>欢迎光临邮件系统,session ID :<?php echo session_id(); ?></p>
25     <form action="login.php" method="post">
26         用户名: <input type="text" name="username"><br>
27         密码:   <input type="password" name="password"><br>
28         <input type="submit" name="sub" value="登录">
29     </form>
30 
31 </body>
32 </html>

  3.index.php中使用session

<?php
    session_start();
    if(isset($_SESSION['islogin']) && $_SESSION['islogin']===1)
    {
        echo "<p>当前用户为:".$_SESSION['username']."<br>";
    }
    else{
            header("Location:login.php");
        }
?>
<html>
...............
</html>


 4.logout.php 删除session
 1  1 <?php
 2  2     session_start();
 3  3     $username = $_SESSION['name'];
 4  4     $_SESSION = array();//删除所有$_SESSION变量
 5  5     if(isset($_COOKIE[session_name()])) //删除包含session的cookie
 6  6     {
 7  7         setcookie(session_name(),'',time()-4200,'/');
 8  8     }
 9  9     session_destroy();
10 10 ?>
11 11 <html>
12 12     ......
13 13 </html>


posted @ 2015-05-12 22:27  白菜hxj  阅读(260)  评论(0编辑  收藏  举报