---
title: "php之cookie会话控制"
author: "kefeng"
date: "2015-03-17T10:19:00Z"
tags: []
slug: "php-cookie"
draft: false
lastmod: "2015-09-09T21:36:51Z"
id: 2242200
url: "https://kefeng.iteye.com/blog/2242200"
---

通过cookie将用户资料记录在客户端而不需要每次都从服务器调用，这样能提高网页效率，降低服务器的压力

下面的例子模拟一个登录界面的操作，使用cookie的调用

界面显示(未进行美化)

![](http://img.blog.csdn.net/20150317102338344?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvaHlmOTM5MjQ=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)

根目录下创建需要的文件

![](http://img.blog.csdn.net/20150317102508481?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvaHlmOTM5MjQ=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)

index.php中，首先写出如图的表格形式输出

```
<html>
	<head>
		<title>用户登录</title>
	</head>
	<body>
		<form action="login.php" method="post">
		<table align="center" border="1" width="300">
			<caption><h1>用户登录</h1></caption>
				<tr>
					<th>用户名</th>
					<td><input type="text" name="name"></td>
				</tr>
				<tr>
					<th>密码</th>
					<td><input type="password" name="password"></td>
				</tr>
				<tr>
					
					<td colspan="2" align="center">
						<input type="submit" name="sub" value="登录">
					</td>
				</tr>
		</table>
	</body>
</html>
```

因为要连接数据库，并调用数据库的数据，创建数据库并创建一个数据库调用的文件

创建一个users的表，并插入数据，这里数据插入信息包括用户名、密码和权限

![](http://img.blog.csdn.net/20150317104028007?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvaHlmOTM5MjQ=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)

在根目录下创建 conn.inc.php 用于存放数据库连接

conn.inc.php

```
<?php
    $mysqli=new mysqli("localhost","root","XXXXX","sqldb");
```

login.php 中包含连接数据库，使用mysqli方法，密码使用 md5() 方法加密

```
<?php
    if(isset($_POST["sub"])){
    	include "conn.inc.php";

    	$sql="select id from users where name='{$_POST["name"]}' and password='".md5($_POST["password"])."'";

    	$result=$mysqli->query($sql);

    	//保存数据
    	if($result->num_rows > 0){
    		$row=$result->fetch_assoc();
    		$time=time()*1800;
    		setCookie("username", $_POST["name"],$time);
    		setCookie("uid", $row["id"],$time);
    		setCookie("isLogin",1);

    		header("Location:index.php");  //跳转界面
    	}
    	echo "用户名密码有误";
    }
?>
```

注意cookie保存数据时需要表明数据保存的时长，保存数据中返回 “username”，“uid”，“isLogin"

index.php 中涉及页面跳转，创建一个公共的跳转页面的类 comm.php

comm.php：如果传回的是 “isLogin” 就进行跳转

```
<?php
    //判断：如果没登录自动跳转到登录页面
    if(!$_COOKIE["isLogin"]){
        header("Location:login.php");
    }
```

登录成功后跳转到 index.php 页面下，登录不成功就返回重新登录

index.php 包含 conn.inc.php 和 comm.php

```
<?php
    include "comm.php";  //判断是否登录成功
    include "conn.inc.php";
    echo "用户<b>".$_COOKIE["username"]."</b>你好!这是网站首页";
    echo "你的权限如下：<br>";
    $sql="select allow_1,allow_2,allow_3,allow_4 from users where id='{$_COOKIE["uid"]}'";
    $result=$mysqli->query($sql);
    $user=$result->fetch_assoc();
    if($user["allow_1"]){
        echo "111111111111<br>";
    }
    if($user["allow_2"]){
        echo "222222222222<br>";
    }
    if($user["allow_3"]){
        echo "333333333333<br>";
    }
    if($user["allow_4"]){
        echo "444444444444<br>";
    }


    ?>

    <a href="test.php">第二页</a><br>
    <a href="test2.php">第三页</a><br>
    <a href="logout.php">退出</a><br>
```

最后第二页、第三页的写法跟 index.php 一样

登出 logout.php 需要注销用户信息

```
<?php
    include "comm.php";  //判断是否登录成功
    
    $username=$_COOKIE["username"];  //取出用户名
    //注销
    setCookie("username");
    setCookie("uid");
    setCookie("islogin");
    echo $username."再见";



?>
<br>
<a href="login.php">重新登录</a>
```

完整代码：

login.php：

```
<?php
    if(isset($_POST["sub"])){
    	include "conn.inc.php";

    	$sql="select id from users where name='{$_POST["name"]}' and password='".md5($_POST["password"])."'";

    	$result=$mysqli->query($sql);

    	//保存数据
    	if($result->num_rows > 0){
    		$row=$result->fetch_assoc();
    		$time=time()*1800;
    		setCookie("username", $_POST["name"],$time);
    		setCookie("uid", $row["id"],$time);
    		setCookie("isLogin",1);

    		header("Location:index.php");  //跳转界面
    	}
    	echo "用户名密码有误";
    }
?>
<html>
	<head>
		<title>用户登录</title>
	</head>
	<body>
		<form action="login.php" method="post">
		<table align="center" border="1" width="300">
			<caption><h1>用户登录</h1></caption>
				<tr>
					<th>用户名</th>
					<td><input type="text" name="name"></td>
				</tr>
				<tr>
					<th>密码</th>
					<td><input type="password" name="password"></td>
				</tr>
				<tr>
					
					<td colspan="2" align="center">
						<input type="submit" name="sub" value="登录">
					</td>
				</tr>
		</table>
	</body>
</html>
```

版权声明：本文为博主原创文章，未经博主允许不得转载。