我正在尝试获取已登录用户的用户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>
最佳答案
首先,我建议您使用PDO代替旧的mysql_query。我对SQL injection更安全。
错误:创建一些简单的“调试”函数以查看变量的输出将是一个好主意。例如,在登录脚本中,您使用var $ result-> 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,它将包含在每个代码中。更改某些功能时,无需重写每个文件。