1.登录时,将用户的SessionID记录下来
2.验证登录时,将记录的该用户SessionID与当前SessionID匹配
3.如果不相同,说明在别处登录
完整实例代码点击此处本站下载。
首先,进入http://localhost/login_single/index.php可查看登录状态。
index.php页面代码如下:
<?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>";
对于未登录的用户则提示跳转到 http://localhost/login_single/login.html登录页面,login.html页面代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>登录</title> </head> <body> <form method="post" action="login.php"> 用户名:<input name="username"><br> 密 码:<input name="password" type="password"><br> <input type="submit" value="登录"> </form> <div> 提示:测试用户名:admin 密码:123 </div> </body> </html>
登录成功后由login.php页面进行相应的session判断。
login.php页面代码如下:
<?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(); }
希望本文所述对大家的php程序设计有所帮助。