Php session variables being lost after redirect

倾然丶 夕夏残阳落幕 提交于 2020-12-15 09:08:07

问题


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';
}

回答1:


I had this problem myself. The solution ended up being that I was not using an absolute URI with the Location: header.

Do this instead of '../home.php' :

header('Location: http://yourdomain.com/home.php');



回答2:


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


来源:https://stackoverflow.com/questions/24390729/php-session-variables-being-lost-after-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!