<?php
//开启Session
session_start();
header("Content-type: text/html; charset=utf-8");
//取Session中的用户信息
$username=$_SESSION['username'];
//判断是否有效
if(!isset($username)){
echo "您未登录!<a href='login.html'>登录</a>";
exit();
}
//登录时保存的该用户SessionID
$sessin_id=file_get_contents('session_id/'.$username);
//如果当前的SessionID与之前记录的SessionID不匹配
//说明已在别处登录
if(session_id() != $sessin_id){
//注销当前用户
unset($_SESSION['username']);
echo "您已在别处登录!<a href='login.html'>从新登录</a>";
exit();
}else{
echo "欢迎您:".$username;
echo " <a href='logout.php'>注销</a>";
}
echo "<p>--这是登录之后才能看到的内容--</p>";
<?php
//开启Session
session_start();
//设置编码
header("Content-type: text/html; charset=utf-8");
//接收表单提交的内容
$username=$_POST['username'];
$password=$_POST['password'];
//模拟验证用户登录
if($username=="admin" && $password=="123"){
//登录成功,将用户名保存到Session中
$_SESSION['username']=$username;
//创建目录
if(!file_exists('session_id')){
mkdir('session_id');
}
//保存的文件名
$filename='session_id/'.$username;
//当前登录用户的SessionId
$session_id=session_id();
//当SessionID保存到对应的文件中
//实际应用,可以保存到数据库、memcache等
file_put_contents($filename,$session_id);
//跳到主页
header ('Location: index.php');
}else{
echo ('<script>alert("登录失败");window.location="login.html"</script>');
exit();
}