2013-01-04 52 views
0

嘿,我還需要與評級系統幫助一點點,但如果cookie存在,這是檢查在PHP腳本中的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])) { 

但由於某種原因,當我添加該腳本的任何工作。

+4

我沒有經歷所有的代碼,但你有一個可能導致問題的$ id和$ ID的混合。 – Sol

回答

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

你宣佈一切爲$ID,但你使用$id。嘗試切換出來,看看它是否工作。

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

我會嘗試 –

+0

哎呀,看起來像別人在評論中回答。他獲得信貸。但它看起來像這是你的問題,所以我會留下來。 – Luciasar00

+0

好吧,它的工作感謝 –

0

我想你想做的事是isset(如果存在)這一翻譯的!isset(如果沒有按牛逼存在)

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

它應該只運行腳本,如果cookie不存在,那麼沒有錯 –