在访问页面之前创建会话

时间:2015-09-25 16:26:39

标签: php session

因此,当用户点击登录时,执行此代码: LoggedIn.php

<?php
include 'connect.php';
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    die ('Username and/or password does not exist!');
}
// Prepare our SQL 
if ($stmt = $mysqli->prepare('SELECT password FROM users WHERE username = ?')) {
    // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
    $stmt->bind_param('s', $_POST['username']);
    if(!$stmt->execute()){
    trigger_error("there was an error....".$mysqli->error, E_USER_WARNING);
    } 
    $stmt->store_result(); 
    // Store the result so we can check if the account exists in the database.
    if ($stmt->num_rows > 0) {
        $stmt->bind_result($password);
        $stmt->fetch();      
        // Account exists, now we verify the password.
        if (password_verify($_POST['password'], $password)) {
            // Verification success! User has loggedin!
            header('location: userPage.php');
                    //**should I create the session here?**

        } else {
            echo 'Incorrect username and/or password!';
        }
    } else {
        echo 'Incorrect username blar password!';
    }
    $stmt->close();
} else {
    echo 'Could not prepare statement!';
}
?> 
如果会话在 userPage.php 上创建,则

这是他们登录时可以访问的页面

<?php
ob_start();
include 'connect.php';
if(!isset($_SESSION['username']) || !isset($_SESSION['password']))
{
    header("location:http://www.fortunefilly.com/loginTemplate.php");
}
else
{
    session_start();
    $username =$_SESSION['username']  ;
}
?>

但是我认为它实际上并没有创建会话,因为我试图回显 $ username ,但它不起作用。关于场景的几点建议会很有帮助

提前谢谢

2 个答案:

答案 0 :(得分:2)

如果您打算使用/创建/取消设置(无论如何)会话,您必须在代码的最开头写session_start();

LoggedIn.php

<?php
include 'connect.php';
session_start();
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    die ('Username and/or password does not exist!');

或者在你的userPage.php中:

<?php
session_start();
ob_start();
include 'connect.php';
if(!isset($_SESSION['username']) || !isset($_SESSION['password']))
{
    header("location:http://www.fortunefilly.com/loginTemplate.php");
}

修改

现在回到问题,你需要set会议,一个很好的地方:

 if (password_verify($_POST['password'], $password)) {
            // Verification success! User has loggedin!

            header('location: userPage.php');
                    //**should I create the session here?**

像牙齿疼痛一样把它拿出来

if(!isset($_SESSION['username'])){ //should do it

答案 1 :(得分:1)

必须在访问会话变量之前启动

会话:

<?php
session_start();
ob_start();
include 'connect.php';
if(!isset($_SESSION['username']) || !isset($_SESSION['password']))
{
    header("location:http://www.fortunefilly.com/loginTemplate.php");
}
else
{
    $username =$_SESSION['username']  ;
}

&GT;