使用PHP SESSION变量的Bug

时间:2015-09-01 20:56:09

标签: php session session-variables

我的应用程序中存储了一个$_SESSION['userId']变量,以了解用户是否已登录,以及用户是什么用户。这是索引中的一段代码:

session_start();
if(!isset($_SESSION['userId']) || empty($_SESSION['userId']) )
{
  header("Location: login.php");
}

并且登录中的代码是相反的。

到目前为止一切正常,我有一个小虫子。我将上面的代码修改为:

session_start();
if(!isset($_SESSION['userId']) || empty($_SESSION['userId']) )
{
  header("Location: login.php");
}else{
  echo "<script>console.log('user id is set');</script>";
}

如果我以这种方式运行,控制台日志会正确显示。但是,如果我将console.log行更改为:echo "<script>console.log('user id=".$_SESSION['userId']."');</script>";,则该网站永远不会加载,并且控制台中不会显示任何错误。

知道会发生什么事吗?只是为了让您知道,我在.php文件中发现了这个错误,该文件使用userId SESSION variable将内容插入到sql数据库中,然后它突然停止工作。

2 个答案:

答案 0 :(得分:0)

Error reporting and/or display_error are probably set to display nothing (production environnement). Try setting them on to see the actual error.

You should escape the quotes of $_SESSION['userId'] with addslashes() or equivalents.

session_start();
if(!isset($_SESSION['userId']) || empty($_SESSION['userId']) )
{
  header("Location: login.php");
}else{
  echo "<script>console.log('user id=".addslashes($_SESSION['userId'])."');</script>";
}

If this doesn't work, the problem is certainly in another part of your code.

答案 1 :(得分:0)

In my point of view, this is not a good idea to use javascript in this context.
The javascript console is not design for php debug
Why don't you just display the sucess login message echo $_SESSION['userId']; ?