无法在会话

时间:2016-06-22 08:52:26

标签: php session

我正在使用php在会话中存储用户名,而我却不能。我要做的是从表单中获取输出,并将其存储到会话中,以便稍后在另一页上获取用户名。

index.php(我从登录表单中获取数据):

if(isset($_POST['submit-login'])){


$uname = $_POST['uname'];
$password = $_POST['password'];
$password = md5($password);

$result = mysqli_query($Conn, "SELECT * FROM `users` WHERE `Username` = '$uname' AND `Password` = '$password'");

$num_rows = mysqli_num_rows($result);

if($num_rows > 0){

    if($uname == "admin"){
        echo "Hello, admin. Do you want to access to the "."<a href='database.php'>database?</a>";

        $name = mysqli_query($Conn, "SELECT `Name` FROM `users` WHERE `Username` = '$uname'");
        $lname = mysqli_query($Conn, "SELECT `Last Name` FROM `users` WHERE `Username` = '$uname'");
        $email = mysqli_query($Conn, "SELECT `Email` FROM `users` WHERE `Username` = '$uname'");
    } else{
    echo "Welcome ".$uname."! You are now logged in!";
    }
} else {
    echo "Sorry, your password and username do not match. Please try again";
}

$_SESSION["uname"] = $_POST['uname'];

}

index.php(我从regsiter表单中获取数据):

if(isset($_POST['submit-register'])){


$uname = $_POST['uname'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$name = $_POST['fname'];
$lname = $_POST['lname'];

if($password2 == $password && $email2 == $email){
    $result = mysqli_query($Conn, "SELECT * FROM `users` WHERE `Username` = '$uname'");
    $num_rows = mysqli_num_rows($result);


    if($num_rows > 0){
        echo "Sorry, that username is already taken.";
    } else {
        mysqli_query($Conn, "INSERT INTO `users` (`Name`, `Last Name`, `Username`, `Password`, `Email`, `Level`) VALUES ('$name', '$lname', '$uname', '$password', '$email', 0)") or die (mysqli_error($Conn));
        echo "Welcome ".$name." ".$lname." (".$uname.")! You are now registered. Log in, please.";
    }
}

$_SESSION["uname"] = $_POST['uname'];
}

me.php:

  <?php
session_start();

$uname = $_SESSION["uname"];
echo $_SESSION["uname"];

?>

在index.php上,我在代码的初始化时启动会话。

在me.php上,回声不打印任何东西!

请帮助,你能告诉我错误在哪里吗?

另外,如果我能用饼干来做这件事就太棒了!但我不知道怎么......

谢谢!

2 个答案:

答案 0 :(得分:1)

您还需要使用session_start()在会话中编写内容。

在index.php中,在顶部添加session_start();

答案 1 :(得分:0)

对于与会话有关的每个文件,您都需要session_start()

顺便说一句,请阅读mysqli_上使用预先准备好的陈述,您当前的代码中充满了漏洞。