会话数据不在页面之间传送

时间:2014-03-31 00:11:22

标签: php session

当用户在我的网站上使用登录系统并且提交的凭据正确时,会设置会话和会话数据。但是sesion数据不会在页面之间传输。在登录脚本中,我打印出会话数组,它显示了所有内容都已设置。但是当我使用打印会话的相同代码进入不同的页面时,它会显示会话中没有任何内容。 (是的,我在每个需要它的php页面的开头插入session_start()

的login.php

<?php

require("config.php"); 

if(!empty($_POST)) 
{ 
    // This query retreives the user's information from the database using 
    // their username. 
    $query = " 
        SELECT 
            id, 
            username, 
            password, 
            salt, 
            email 
        FROM users 
        WHERE 
            username = :username 
    "; 

    // The parameter values 
    $query_params = array( 
        ':username' => $_POST['username'] 
    ); 

    try 
    { 
        // Execute the query against the database 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex) 
    { 

        die("Failed to run query: " . $ex->getMessage()); 
    } 


    $login_ok = false; 


    $row = $stmt->fetch(); 
    if($row) 
    { 

        $check_password = hash('sha256', $_POST['password'] . $row['salt']); 
        for($round = 0; $round < 65536; $round++) 
        { 
            $check_password = hash('sha256', $check_password . $row['salt']); 
        } 

        if($check_password === $row['password']) 
        { 
            // If they do, then we flip this to true 
            $login_ok = true; 
        } 
    } 

    // If the user logged in successfully, then we send them to the private members-only page 
    // Otherwise, we display a login failed message and show the login form again 
    if($login_ok) 
    { 

        unset($row['salt']); 
        unset($row['password']);  
        $_SESSION['USER'] = $row; 


        /* print_r($_SESSION); */

        session_write_close();
        header("Location: index.php"); 
        // Redirect the user to the index page. 
        die("Redirecting to the home page."); 
    } 
    else 
    { 
        print("Login Failed."); 

        $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); 
        header("Location: login.php");
        exit;
    } 
} 
echo $message; 
?>

下一个脚本会检查会话是否已设置。如果不是,则将用户重定向到登录页面。

<?php

/*** begin the session ***/
session_start();

if(!isset($_SESSION['USER']))
{ 
    // If they are not, we redirect them to the login page. 
    header("Location: ../login.php"); 
    exit;
} 
?>

1 个答案:

答案 0 :(得分:1)

你也必须在Login.php上使用session_start();