php会话以对登录表单上的用户进行身份验证 [英] php sessions to authenticate user on login form

查看:54
本文介绍了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.

推荐答案

使用此设置会话的方法

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");

这篇关于php会话以对登录表单上的用户进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆