为什么我不能在PHP中的多个文件中访问会话变量?

时间:2013-12-25 13:47:22

标签: php session

我有一个登录检查器,如果检查成功,会将用户重定向到主页。我将会话变量中的用户名保存为'用户名'索引。

<?php

ob_start();
include("db.php");
session_start();
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];


$sql="SELECT * FROM users WHERE username='$myusername' and password='$mypassword'";
$result=pg_query($sql);

$count=pg_num_rows($result);

if($count==1){
$_SESSION['username'] = $myusername;
header("location:homepage.php");
}
else {
    echo "Wrong Username or Password";
}
ob_end_flush();
?>

我尝试访问索引但得到一个不存在的错误

 <p>WELCOME!</p>
<?php
session_start();
echo $_SESSION['username'];

我在每个文件中调用session_start,所以我看不到问题。

3 个答案:

答案 0 :(得分:0)

   Check  your $count variable's  value, 
   I think your  session is not creating due to your conditions.

   If your $count value will 1 then it will print session's value.

   Your code is fine, no need to change the code, only check your conditions.

   I am sure your issue will be solve.  

   Change
   if($count==1){
          $_SESSION['username'] = $myusername;
          header("location:homepage.php");
      } 
   To 

    if($count){
          $_SESSION['username'] = $myusername;
          header("location:homepage.php");
      } 

答案 1 :(得分:0)

试试这个:

<?php
include("db.php");
session_start();
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

if($myusername!="" and $mypassword!="")
{
    $sql="SELECT * FROM users WHERE username='$myusername' and password='$mypassword'";
    $result=pg_query($sql);

    $count=pg_num_rows($result);

    if($count==1)
    {
        $_SESSION['username'] = $myusername;
        header("location:homepage.php");
    }
    else {
        echo "Wrong Username or Password";
    }
}else {
    echo "Please Enter Username and Password";
}
?>

答案 2 :(得分:0)

如果有人输入' or 1 or '密码怎么办?做好消毒工作。

缺少$_SESSION['username']

首先检查$ count的值以验证凭据是否正确。

如果可以,请检查您的浏览器。 php会话基于cookie值。检查您的浏览器是否允许使用cookies。

如果允许,则查找名为PHPSESSID的cookie,如果其设置且有效。

这样你就可以确定你的问题。

this extension可以帮助检查chrome中的Cookie值。

相关问题