无法在会话

时间:2016-11-27 12:09:10

标签: php html mysql session-variables

我正在尝试获取已登录用户的用户ID并将其存储在会话中,这样当用户提交内容时,我可以将他们的用户ID添加到数据库的提交中。我有一个非常粗略的登录页面,请善待,因为我对这一切都很新!我已经尝试了很多不同的组合,但是按照我在网上看到的答案,我现在所拥有的应该非常接近。如果有人能给我任何指示,那将是一个很大的帮助。谢谢!

登录页面

<?php

session_start();

//Connection and select database go in here

// username and password sent from form
$myusername=$_POST['Email'];
$mypassword=$_POST['User_Password'];

// To protect MySQL injection 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT User_ID, Email, User_Password FROM $tbl_name WHERE Email='$myusername' and User_Password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row counts table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// is_auth to make sure they can view other pages that need credentials.
$_SESSION['is_auth'] = true;
$_SESSION['User_ID'] = $result->User_ID;

// Once the sessions variables have been set, redirect them to the landing page / home page.
header('location: ../View/main.php');
exit;
 }

else {
$error = "Please enter an email and password to login.";
}
header("location:../View/mainUnauthenticated.php");

检查用户是否经过身份验证的页面。我在每个相关页面的开头都称之为

<?php

    session_start();
echo $_SESSION['User_ID'];

// Test the session to see if is_auth flag was set (meaning they logged in successfully)

// If test fails, send the user to homepage and prevent rest of page being shown.

if (!isset($_SESSION["is_auth"])) {
header("location: ../View/mainUnauthenticated.php");
exit;
    }
else if (isset($_REQUEST['logout']) && $_REQUEST['logout'] == "true") {
// At any time we can logout by sending a "logout" value which will unset the "is_auth" flag.
// We can also destroy the session if so desired.
unset($_SESSION['is_auth']);
session_destroy();
// After logout, send them back to homepage
header("location: ../View/mainUnauthenticated.php");
exit;
}
?>

这是其中一个页面的片段,我希望能够获取我认为存储的用户ID。现在我只是想让它显示在文本字段中以显示它正在工作。

<?php include('../Controller/is_auth.php') 

?>


<p>
<input type="text" name="User_ID" id="User_ID" value="<?php echo $_SESSION['User_ID'];?>"/>
</p>

1 个答案:

答案 0 :(得分:0)

首先,我建议您使用PDO而不是旧的mysql_query。我对SQL injection更安全。

错误:最好创建一些简单的“调试”函数来查看变量的输出。例如,在您的登录脚本中,您使用var $ result-&gt; User_ID。你确定该变量存在吗?这是我可以使用的简单调试功能:

function debug ($var, $name = "Debug") {
    echo "<h2>$name</h2><pre>";
    var_dump($var);
    echo "</pre>";
}

使用此功能,您只需检查您是否得到了除外,并发现问题。只需致电

debug($result, "Database output");//or without 2nd parameter

PS:创建一些您将在每个代码中包含的functions.php。当你改变某些功能时,你不需要重写每个文件。