2014-02-20 169 views
0

there!我寫了一段代碼來對抗我的網站vistor沒有刷新。以下是我的代碼,任何人都可以給我一些關於代碼的提示,並給出一些建議?php counter避免刷新

<?php 

    $counterFile='counter.txt'; 
    $ipFile='ip.txt'; 
    if(!is_file($counterFile)){ 
     file_put_contents($counterFile,0); 
    } 
    if(!is_file($ipFile)){ 
     file_put_contents($ipFile,0); 
    } 


    $handle=fopen($counterFile,'rb') or die('error:can not open the counter file'); 
    $fileSize=filesize($counterFile); 
    $counter=intval(fread($handle,$fileSize)); 
    fclose($handle); 
    /**----$counter=file_get_contents($counterFile);----***/ 

    $oldIp=file_get_contents($ipFile); 
    $currIp=$_SERVER['REMOTE_ADDR']; 
    //echo $oldIp.'==='.$currIp; 


    if($oldIp!=$currIp){ 
     ++$counter; 
     $handle=fopen($counterFile,'wb'); 
     fwrite($handle,$counter); 
     fclose($handle); 
     /**----file_put_contents($counterFile,$counter);----***/ 
    } 


    file_put_contents($ipFile,$currIp); 


    echo $counter; 

?> 
+0

OMFG。人們還在做櫃檯嗎? –

+4

這個問題似乎是無關緊要的,因爲它涉及代碼審查,因此更適合http://codereview.stackexchange.com/。 – Carsten

+2

爲什麼不使用Google Analytics等網絡統計信息? – Pitchinnate

回答

0

您可以使用Google Analytics或基本統計數據包。或者你可以通過ip地址來跟蹤他們,其中來自一個ip地址的一個人是一個訪問者。或者您可以使用cookie,您可以在訪客第一次請求時設置cookie,以便確定來自同一訪問者的進一步請求

+0

IP地址不是一個好的解決方案。你可能有50個不同的人在一個辦公室的同一個外部IP地址上,而且只會計算一次。 – Pitchinnate

+0

所以我會說使用谷歌分析。這是您可以獲得的最佳解決方案。 – hellosheikh

+0

我寫這段代碼只是爲了實踐,但仍然非常坦克!你給我一些提示! – ChainWay

0

您可以使用魔術方法__destruct序列化破壞對象,並創建一個靜態函數,以提供新實例如果存在序列化的一個:

<?php 

class Counter { 
    const CACHE_FILE = '/tmp/counter.clss'; 
    protected $_counter = 0; 
    public function up(){ 
    $this->_counter++; 
    } 

    public function down(){ 
    $this->_counter--; 
    } 

    public function howmany(){ 
    print $this->_counter; 
    } 

    public function __destruct(){ 
    file_put_contents(self::CACHE_FILE,serialize($this)); 
    } 

    public static function retrieve(){ 
    if(file_exists(self::CACHE_FILE)){ 
     $obj = unserialize(file_get_contents(self::CACHE_FILE)); 
    }else{ 
     $obj = new self; 
    } 
    return $obj; 
    } 
} 
$ctr = Counter::retrieve(); 
$ctr->up(); 
$ctr->howmany(); 

然後調用該文件,如果時間文件存在,將重新創建對象,然後和計數器:

~$ php counter.php 
1 
~$ php counter.php 
2 
~$ php counter.php 
3