我有以下代码用于开始会话并存储用户名/密码数据,如果没有提交任何内容,或者没有存储会话数据,则重定向到失败页面.
session_start(); if(isset($_POST['username']) || isset($_POST['password'])) { $username = $_POST['username']; $password = $_POST['password']; $_SESSION['username'] = $username; $_SESSION['password'] = $password; } if(isset($_SESSION['username']) || isset($_SESSION['password'])){ $navbar = "1"; $logindisplay = "0"; $username = $_SESSION['username']; $password = $_SESSION['password']; } else { header('Location:http://website.com/fail.PHP'); } $authed = auth($username,$password); if( $authed == "0" ){ header('Location:http://website.com/fail.PHP'); }
即使我提交了我的信息并将其存储在会话中,它也没有按照应有的方式工作,并且正在重定向我失败.难道我做错了什么?
解决方法
怎么用这个来设置会话
session_start(); if( isset($_POST['username']) && isset($_POST['password']) ) { if( auth($_POST['username'],$_POST['password']) ) { // auth okay,setup session $_SESSION['user'] = $_POST['username']; // redirect to required page header( "Location: index.PHP" ); } else { // didn't auth go back to loginform header( "Location: loginform.html" ); } } else { // username and password not given so go back to login header( "Location: loginform.html" ); }
session_start(); session_regenerate_id(); if(!isset($_SESSION['user'])) // if there is no valid session { header("Location: loginform.html"); }
这样可以在每个页面的顶部保留非常少量的代码,而不是在每个页面的顶部运行完整的auth.要注销会话:
session_start(); unset($_SESSION['user']); session_destroy(); header("Location: loginform.html");