Home > php教程 > PHP源码 > body text

php中利用session验证登录表单

WBOY
Release: 2016-06-08 17:20:20
Original
1440 people have browsed it

前段时间在做一个中奖的活了,其中就用到中奖之后把数据写入session 然后再由用户进行数据提交验证了,下面我们要介绍的不是那个例子而一个差不多例子了,具体如下。

<script>ec(2);</script>

登录页面是:





登陆



姓名:

密码:






存储session的页面:

header("Content-Type: text/html; charset=utf8");
if( !isset($_POST["submit"]) ){
die("错误执行");
}//检测是否有submit操作
 
require_once('connect.php');//链接数据库
 
if ( isset($_POST['name']) && isset($_POST['password']) ){//如果用户名和密码都不为空
 
$name = $_POST['name'];
 
$password = $_POST['password'];
 
$sql = " SELECT id, limits, message FROM user WHERE username = '$name' AND password = '$password' LIMIT 1";
 
$result = mysqli_query( $con , $sql );//执行sql 用户名和密码
 
$rows = mysqli_num_rows( $result );//返回用户名密码是否存在
 
if( $rows != 0 ){
 
session_start();
 
while( $rows_other = mysqli_fetch_assoc($result) ){
 
$_SESSION['id'] = $rows_other['id'];
$_SESSION['name'] = $name;
$_SESSION['limits'] = $rows_other['limits'];
$_SESSION['message'] = $rows_other['message'];
 
}
 
header("refresh:0;url=welcome.php");//跳转至welcome.html页面
 
exit;
 
}else{
 
echo "用户名或密码错误";
 
echo "<script><br /> alert('用户名或密码错误');<br /> setTimeout(function(){window.location.href='login.html';},1000);<br /> </script>";
 
}
 
}else{
 
echo "表单填写不完整";
 
echo "<script><br /> alert('表单填写不完整');<br /> setTimeout(function(){window.location.href='login.html';},1000);<br /> </script>";
 
}
?>

登陆后跳转的页面,根据不同的用户显示不同的权限和用户名:

 




Document


 
 
session_start();
 
if( isset($_SESSION['id']) ){
 
require_once('connect.php');
 
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$limits = $_SESSION['limits'];
$message = $_SESSION['message'];
 
if( $limits == 1 ){
 
echo 'hello, 管理员' . '
';
 
}else{
 
echo 'helo, 普通用户' . '
';
}
 
echo 'hello you name is:' . $name;
 
}else{
 
echo '未登录!';
 
header("refresh:3;url=login.html");
 
}
?>
 
 


?>

使用session注意事项

1.在当前页面要使用session时我们在文件最前面没有输入内容时加上session_start();

2.session有一个时间限制的这个我们可以进行修改的,具体如下

 其实PHP5 Session还提供了一个函数 session_set_cookie_params(); 来设置PHP5 Session的生存期的,该函数必须在 session_start() 函数调用之前调用:

    // 保存一天
    $lifeTime = 24 * 3600;
    session_set_cookie_params($lifeTime);
    session_start();
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!