无法在会话中存储用户ID

问题描述:

我试图获取登录用户的用户ID并将其存储在会话中,以便当用户提交某些内容时,我可以将其用户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

不要使用'mysql'来代替'mysqli'或'PDO',您也可以使用'mysql injection'。 – Nytrix

+0

我想我现在已经开始工作了。问题在于我的会话开始的位置,我把它放在我的登录页面的顶部,但将它移到sql查询之后并且它正在工作!感谢Nytrix和Filip Macek的帮助和评论。 –

首先,我建议您使用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,您将在每个代码中包含这些函数。当你改变一些功能时,你不需要重写每一个文件。