重定向后 PHP 会话变量丢失 [英] Php session variables being lost after redirect

查看:54
本文介绍了重定向后 PHP 会话变量丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我已经找了几个星期来解决这个问题.我有一个登录代码,在输入信息以登录表单后,将信息发送到一个 php 页面,该页面运行一个包含检查该数据库并保存信息(如果匹配)的函数,然后返回 true.php 页面然后重定向到主页,该主页运行登录的检查功能,但会话不在那里.

我已经确定我有 session_start();在所有页面的顶部标题有一个 exit();在它之后,重定向是 header('Location: ../home.php');我检查了 phpinfo();我试过 session_write_close();和 session_regenerate_id(true);, session_regenerate_id();iv 检查了会话保存路径/temp

会话一直保存,直到重定向 iv 随处回显检查每个帮助站点和页面

这是登录

 if (login($email, $password, $mysqli) == true) {//登录成功session_write_close();header('位置:../home.php');出口();} 别的 {//登录失败header('位置:../signIn.php?error=1');出口();}

我将会话保存在登录函数中,当我在此处回显时,它们仍然存在,但在重定向后,我在 loginCheck 函数中回显,但什么也没有.

这是我使用的会话函数

function sec_session_start() {$session_name = 'sec_session_id';$secure = '安全';$httponly = true;if (ini_set('session.use_only_cookies', 1) === FALSE) {header("位置:../error.php?err=无法启动安全会话(ini_set)");出口();}$cookieParams = session_get_cookie_params();session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);会话名称($会话名称);session_start();session_regenerate_id();}

这是我的 loginCheck dosent 使它通过第一个如果没有会话

function login_check($mysqli) {//检查是否设置了所有会话变量回声 $_SESSION['你好'];回声 $_SESSION['用户名'];回声 $_SESSION['user_id'];echo $_SESSION['login_string'];echo '你好';如果 (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {//if ($_SESSION['Logging'] == "correct") {echo '你好';$user_id = $_SESSION['user_id'];$login_string = $_SESSION['login_string'];$username = $_SESSION['username'];//获取用户的用户代理字符串.$user_browser = $_SERVER['HTTP_USER_AGENT'];if ($stmt = $mysqli->prepare("选择密码来自 company_users哪里 id = ?限制 1")) {//将$user_id"绑定到参数.$stmt->bind_param('i', $user_id);$stmt->execute();//执行准备好的查询.$stmt->store_result();如果 ($stmt->num_rows == 1) {//如果用户存在,则从结果中获取变量.$stmt->bind_result($password);$stmt->fetch();$login_check = hash('sha512', $password . $user_browser);如果($login_check == $login_string){//登录!!!!返回真;} 别的 {//未登录返回假;}} 别的 {//未登录返回假;}} 别的 {//未登录返回假;}} 别的 {//未登录返回假;}}

这是表格

<div class="form-group"><label class="col-lg-2 control-label ">Email</label><div class="col-lg-10"><input class="form-control textBox" id="email" name='email' placeholder="Email" type="email">

<div class="form-group"><label class="col-lg-2 control-label">密码</label><div class="col-lg-10"><input class="form-control textBox" id="password" nam='password' placeholder="Password" type="password">

<div class="form-group"><label class="col-lg-2 control-label"></label><div class="col-lg-10"><input class="btn btn-success" type="button" value='Login' onclick='formhash(this.form, this.form.password);'>

</表单>

这是登录功能

function login($email, $password, $mysqli) {//使用预处理语句意味着 SQL 注入是不可能的.if ($stmt = $mysqli->prepare("SELECT id, username, password, salt来自 company_usersWHERE 电子邮件 = ?限制 1")) {$stmt->bind_param('s', $email);//将$email"绑定到参数.$stmt->execute();//执行准备好的查询.$stmt->store_result();//从结果中获取变量.$stmt->bind_result($user_id, $username, $db_password, $salt);$stmt->fetch();//用唯一的盐散列密码.$password = hash('sha512', $password . $salt);如果 ($stmt->num_rows == 1) {//如果用户存在,我们检查帐户是否被锁定//登录尝试次数过多如果(checkbrute($user_id,$mysqli)==真){//账户被锁定//向用户发送一封电子邮件,说他们的帐户被锁定返回假;} 别的 {//检查数据库中的密码是否匹配//用户提交的密码.如果($db_password == $password){//密码正确!//获取用户的用户代理字符串.$user_browser = $_SERVER['HTTP_USER_AGENT'];//XSS 保护,因为我们可能会打印此值$user_id = preg_replace("/[^0-9]+/", "", $user_id);$_SESSION['user_id'] = $user_id;//XSS 保护,因为我们可能会打印此值$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);$_SESSION['username'] = $username;$_SESSION['login_string'] = hash('sha512', $password . $user_browser);返回真;//echo $_SESSION['用户名'];//echo $_SESSION['user_id'];//echo $_SESSION['login_string'];//登陆成功.} 别的 {//密码不正确//我们在数据库中记录这次尝试$现在=时间();$mysqli->query("INSERT INTO login_attempts(user_id, time)值 ('$user_id', '$now')");返回假;}}} 别的 {//没有用户存在.返回假;}//$_SESSION['check'] = '你好';}}

登录验证

解决方案

使代码尽可能简单.不需要回显来确认会话已设置.您需要一起重新设计流程

Hello i have been looking for weeks to solve this. i have a login code that after entering you information to log in the form sends the information to a php page that runs a function from an include that checks that database and saves the information if it matches, then returns true. the php page then redirects to home page that runs a logged in check function but the sessions are not there.

I have made sure that i have session_start(); at the top of all pages the header has a exit(); after it and the redirect is header('Location: ../home.php'); i have checked the phpinfo(); i tried session_write_close(); and session_regenerate_id(true);, session_regenerate_id(); iv checked the Session save path /temp

the sessions save all up till till the redirect iv echoed everywhere checked every help site and page

this is the login

    if (login($email, $password, $mysqli) == true) {
    // Login success
    session_write_close();
    header('Location: ../home.php');
    exit();
} else {
    // Login failed 
    header('Location: ../signIn.php?error=1');
    exit();
}

i save the sessions in the login function and when i echo it here they are still there but after the redirect i echo in the loginCheck function and there is nothing.

this is the session function im using

function sec_session_start() {
$session_name = 'sec_session_id';
$secure = 'SECURE';

$httponly = true;

if (ini_set('session.use_only_cookies', 1) === FALSE) {
    header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
    exit();
}

$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);

session_name($session_name);
session_start();
session_regenerate_id();
}

this is my loginCheck dosent make it passed the first if cuz of no sessions

function login_check($mysqli) {
// Check if all session variables are set 
echo $_SESSION['hello'];
echo $_SESSION['username'];
echo $_SESSION['user_id'];
echo $_SESSION['login_string'];
echo 'hello';

if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
//if ($_SESSION['Logging'] == "correct") {
    echo 'hello';
    $user_id = $_SESSION['user_id'];
    $login_string = $_SESSION['login_string'];
    $username = $_SESSION['username'];

    // Get the user-agent string of the user.
    $user_browser = $_SERVER['HTTP_USER_AGENT'];


    if ($stmt = $mysqli->prepare("SELECT password 
                                  FROM company_users 
                                  WHERE id = ? LIMIT 1")) {
        // Bind "$user_id" to parameter. 
        $stmt->bind_param('i', $user_id);
        $stmt->execute();   // Execute the prepared query.
        $stmt->store_result();

        if ($stmt->num_rows == 1) {
            // If the user exists get variables from result.
            $stmt->bind_result($password);
            $stmt->fetch();
            $login_check = hash('sha512', $password . $user_browser);

            if ($login_check == $login_string) {
                // Logged In!!!! 
                return true;
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    } else {
        // Not logged in 
        return false;
    }
} else {
    // Not logged in 

    return false;
  }
}

this is the form

<form class="form-horizontal" action="includes/signInValidation.php"  method="POST" name='login_form'>

        <div class="form-group">
            <label class="col-lg-2 control-label ">Email</label>
            <div class="col-lg-10">
                <input class="form-control textBox" id="email" name='email' placeholder="Email" type="email">
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-2 control-label ">Password</label>
            <div class="col-lg-10">
                <input class="form-control textBox" id="password" nam='password' placeholder="Password" type="password">
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-2 control-label "></label>
            <div class="col-lg-10">
                <input class="btn btn-success"  type="button" value='Login' onclick='formhash(this.form, this.form.password);' >
            </div>
        </div>
    </form>

this is the login function

function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt 
    FROM company_users
   WHERE email = ?
    LIMIT 1")) {
    $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
    $stmt->execute();    // Execute the prepared query.
    $stmt->store_result();


    // get variables from result.
    $stmt->bind_result($user_id, $username, $db_password, $salt);
    $stmt->fetch();

    // hash the password with the unique salt.
    $password = hash('sha512', $password . $salt);
    if ($stmt->num_rows == 1) {
        // If the user exists we check if the account is locked
        // from too many login attempts 

        if (checkbrute($user_id, $mysqli) == true) {
            // Account is locked 
            // Send an email to user saying their account is locked
            return false;
        } else {
            // Check if the password in the database matches
            // the password the user submitted.
            if ($db_password == $password) {

                // Password is correct!
                // Get the user-agent string of the user.
                $user_browser = $_SERVER['HTTP_USER_AGENT'];
                // XSS protection as we might print this value
                $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                $_SESSION['user_id'] = $user_id;
                // XSS protection as we might print this value
                $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
                $_SESSION['username'] = $username;
                $_SESSION['login_string'] = hash('sha512', $password . $user_browser);

                return true;




                //echo $_SESSION['username'];
                //echo $_SESSION['user_id'];
                //echo $_SESSION['login_string'];
                // Login successful.

            } else {
                // Password is not correct
                // We record this attempt in the database
                $now = time();
                $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                VALUES ('$user_id', '$now')");
                return false;
            }
        }
    } else {
        // No user exists.
        return false;
    }

    //$_SESSION['check'] = 'hello';
  }
}

signInValidation

<?php
include_once 'db/dbConnect.php';
include_once 'functions.php';
sec_session_start();
if (isset($_POST['email'], $_POST['p'])) {
    $email = $_POST['email'];
    $password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
    // Login success
    //$_SESSION['loggedIn'] = 'true';
    session_write_close();
    header('Location: ../profile.php');
    exit();
} else {
    // Login failed 
    header('Location: ../signIn.php?error=1');
    exit();
}
} else {
    // The correct POST variables were not sent to this page. 
    echo 'Invalid Request';
}

解决方案

Make codes as simple as possible. there is no need echoing to confirm session is set. You need to redesign the process all together

<?php

session_start();


if ( !isset(  $_SESSION['user_id'] ) )

  { header("location:index");
}

这篇关于重定向后 PHP 会话变量丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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