php 会话在登录表单上对用户进行身份验证
我有以下代码用于开始会话并存储用户名/密码数据,如果没有提交任何内容或没有存储会话数据,则重定向到失败页面.
I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.
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');
}
即使我提交了我的信息并将其存储在会话中,它也没有按应有的方式工作并且正在重定向我失败.难道我做错了什么?
Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?
注意在我添加会话代码之前,经过身份验证的函数运行良好.
NOTE the authed function worked fine before i added the session code.
如何使用它来设置会话
what about using this to setup session
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" );
}
并在每个安全"页面的顶部使用此代码:
and at the top of each "secure" page use this code:
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
这会在每个页面的顶部保留非常少量的代码,而不是在每个页面的顶部运行完整的身份验证.退出会话:
this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:
session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");