用户在访问论坛或者社交网站时,若想进行回帖发帖等操作。都会被要求在登录以后才可以实现。在本例中,使用$_SESSION预定义变量存储用户的会话信息。通过判断次会话信息来实现对论坛发帖权限的验证和管理。
实例代码:
login.php
PHP
<?php
session_start();
if(isset($_POST['btn']))
{
if(($_POST['un']=='admin') && ($_POST['pwd']=='admin')){
$_SESSION['user'] = $_POST['un'];
$_SESSION['pwd'] = $_POST['pwd'];
echo "<script>alert('登录成功!');location='session.php';</script>";
}else
{
echo "<script>alert('用户名密码错误!!');location='login.php';</script>";
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action=""method="post">
<h2>用户登录</h2>
<div>
用户名:<input type="text" name="un">
</div>
<div>
密码: <input type="password" name="pwd">
</div>
<input type="submit" value="登录" name="btn">
</form>
</div>
</body>
</html>
session.php
PHP
<?php
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h2>编辑或者发布新贴</h2>
</div>
<?php if($_SESSION['user']) {?>
<div class="show2">
<div style="float: left;margin-right: 20px;">
<div>用户名:</div>
<img src="img/1.png" alt="头像" style="width: 80px;height: 80px;">
</div>
<div style="float:left">
<textarea rows="10" cols="100"></textarea>
</div>
<div style="clear: both;"></div>
<div>
<input type="submit" value="发帖">
</div>
</div>
<?php } else {?>
<div class="show2">
<h2>论坛发帖:检测当前用户未登录</h2>
<p>请用户: <a href="login.php">登录</a> | <a href="login.php">注册</a> </p>
</div>
<?php }?>
</body>
</html>