检查PHP脚本中的cookie

时间:2013-01-04 15:35:36

标签: php javascript jquery ajax cookies

嘿,我仍然需要对评级系统提供一些帮助,但我在检查cookie是否存在时遇到问题

<?php

    $rating = new ratings($_POST['widget_id']);


    isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();





class ratings {

    var $data_file = './ratings.data.txt';
    private $widget_id;
    private $data = array();


function __construct($wid) {

    $this->widget_id = $wid;

    $all = file_get_contents($this->data_file);

    if($all) {
        $this->data = unserialize($all);
    }
}

public function get_ratings() {
    if($this->data[$this->widget_id]) {
        echo json_encode($this->data[$this->widget_id]);
    }
    else {
        $data['widget_id'] = $this->widget_id;
        $data['number_votes'] = 0;
        $data['total_points'] = 0;
        $data['dec_avg'] = 0;
        $data['whole_avg'] = 0;
        echo json_encode($data);
    } 
}
public function vote() {

    # Get the value of the vote
    preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
    $vote = $match[1];

    $ID = $this->widget_id;
    # Update the record if it exists

    # doesn't update if it already exists
    if (!isset($_COOKIE[$id])) {

    if($this->data[$ID]) {
        $this->data[$ID]['number_votes'] += 1;
        $this->data[$ID]['total_points'] += $vote;
    }
    # Create a new one if it doesn't
    else {
        $this->data[$ID]['number_votes'] = 1;
        $this->data[$ID]['total_points'] = $vote;
    }

    $this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
    $this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );


    file_put_contents($this->data_file, serialize($this->data));
    $this->get_ratings();
}
} //ends if isset
# ---
# end class
}

?>

应检查cookie是否存在的部分是:

if (!isset($_COOKIE[$id])) {

但由于某种原因,当我添加它时脚本中没有任何内容。

2 个答案:

答案 0 :(得分:1)

if (!isset($_COOKIE[$id])) { 

您已将所有内容声明为$ID,但您使用的是$id。尝试将其切换出来,看看它是否有效。

if (!isset($_COOKIE[$ID])) {

答案 1 :(得分:0)

我认为你想做的是isset(如果存在)而不是!isset(如果不存在)

if (isset($_COOKIE[$id])) {