代码只放通过SID判断使用cookie还是session
login.php
<?php
session_start();
echo session_id()."<br>"; //跳转页面不能不是header
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();
$_SESSION["username"]=$_POST["name"];
$_SESSION["uid"]=$_POST["uid"];
$_SESSION["isLogin5"]=1;
//跳转界面
echo '<script>';
echo "location='index.php?".SID."'"; //SID 常量如果开启cookie则使用cookie,如果没开启就用session
echo '</script>';
}
echo "用户名密码有误";
}
?>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<form action="login.php?<?php echo SID; ?>" 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>
conn.inc.php
<?php
$mysqli=new mysqli("localhost","root","heyifeng19930924","sqldb");
comm.php
<?php
session_start();
//判断:如果没登录自动跳转到登录页面
if(!$_SESSION["isLogin5"]){
header("Location:login.php");
}
index.php
<?php
include "comm.php"; //判断是否登录成功
include "conn.inc.php";
echo "用户<b>".$_SESSION["username"]."</b>你好!这是网站首页";
echo session_id()."<br>";
echo "你的权限如下:<br>";
$sql="select allow_1,allow_2,allow_3,allow_4 from users where id='{$_SESSION["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?<?php SID ?>">第二页</a><br>
<a href="test2.php?<?php SID ?>">第三页</a><br>
<a href="logout.php?<?php SID ?>">退出</a><br>
test.php和test2.php编写上和index.php如出一辙
logout.php
<?php
include "comm.php"; //判断是否登录成功
$username=$_SESSION["username"]; //取出用户名
$sid=session_id();
//开启session
session_start();
//情况session值
$_SESSION=array();
//删除客户端的在cookie中的sessionid
if(isset($_COOKIE[session_name()])){
setCookie(session_name(),'',time()-3600,'/'); //一定要写上第四个参数(路径)
}
//彻底销毁session
session_destroy();
echo $username."再见!";
echo $sid;
?>
<br>
<!--
<a href="login.php?PHPSESSID=<?php echo session_id() ?>">重新登录</a>
-->
<a href="login.php">重新登录</a>