比较php类中的会话变量?

时间:2012-10-09 20:04:18

标签: php ajax class session

我正在尝试从类函数中设置会话变量的值,并在稍后的某个时间内在同一个类的不同函数内比较该会话值。这些函数都不在__construct()函数中。

问题似乎是比较永远不会返回true。

<?php
session_start();
$class = new Class();
?>

blah blah blah

<script type="text/javascript">
    // Ajax function to call PHP that creates new Class isntance and executes a Class->function();
    setInterval('checkNew()', 10000);
</script>

blah blah blah

// Another Ajax Function that calls creates a new Class isntance and executes the initial Class->function();
<body onload="getMessages();">

blah blah blah

下一个功能摘录是从<body onload=""> ajax调用的脚本运行的。 这是为了稍后在另一个函数中比较$_SESSION['last_sms']

// Check the now() stamp of the most recent message loaded
$recent_msg_query = "SELECT date_received FROM messages ORDER BY date_received DESC LIMIT 1";
$recent_statement = $this->db_handle->prepare($recent_msg_query);
$recent_statement->execute();
$most_recent = $recent_statement->fetch(PDO::FETCH_NUM);
$_SESSION['last_sms'] = $most_recent[0];

这是Class中应该进行比较的函数,每十秒钟一次(通过setInterval('checkNew()', 10000);

public function checkNew()
{
    // Check the now() stamp of the most recent message loaded and compares it
    // to a stored now() stamp.
    $recent_msg_query = "SELECT date_received FROM messages ORDER BY date_received DESC LIMIT 1";
    $recent_statement = $this->db_handle->prepare($recent_msg_query);
    $recent_statement->execute();
    $most_recent = $recent_statement->fetch(PDO::FETCH_NUM);

    if (!isset($_SESSION['last_sms'])) {
        $_SESSION['last_sms'] = $most_recent[0];
    }

    if ($_SESSION['last_sms'] !== $most_recent[0]) {
        echo "New message(s) available, refresh.";
    } else {
        echo "No new messages yet.";
    }
}

当我发送新邮件时,该页面仍显示“尚未收到新邮件”。你能帮助我弄清楚我在这里走的路吗?到目前为止,这$_SESSION stuff是唯一不起作用的。

1 个答案:

答案 0 :(得分:1)

session_start()不仅仅用作会话发起者。必须在每个尝试读取或写入$_SESSION脚本上调用它。由于您的AJAX处理程序脚本与生成调用它们的页面的主PHP脚本分离,并且它们作为完全独立的PHP脚本运行,您还必须在处理PHP脚本的AJAX上调用session_start()