PHP命中计数器与DATE

时间:2015-09-19 14:43:42

标签: php file web

我使用以下代码作为点击计数器:

$fp = fopen("counterlog.txt", "r"); 
$count = fread($fp, 1024); 
fclose($fp); 
$count = $count + 1; 
$fp = fopen("counterlog.txt", "w"); 
fwrite($fp, $count); 
fclose($fp); 

在文件中我只有一个数字,但我想通过以下方式获取文件:

18/09/2015  10
19/09/2015  11

所以我希望按日期和日期分组的计数用标签分隔。

我知道我可以使用数据库来做到这一点,但在这种特定情况下我只想使用文本文件。

有可能获得吗?

3 个答案:

答案 0 :(得分:2)

这应符合您的要求。

<?php


$dateexists = false;

if(!file_exists('counterlog.txt'))
{
    $fh = fopen('counterlog.txt', 'w');
    fclose($fh);
}

$datecounts = file('counterlog.txt', FILE_IGNORE_NEW_LINES);
foreach($datecounts as $key => $datecount){

    list($date, $count) = explode("\t", $datecount);

    $count = (int) $count;
    if($date == date('d/m/Y'))
    {
        $datecounts[$key] = $date."\t".++$count;
        $dateexists = true;
    }
}
if(!$dateexists)
{
    $datecounts[] = date('d/m/Y')."\t1";
}

$fh = fopen('counterlog.txt', 'w');
if (flock($fh, LOCK_EX)) {
    foreach($datecounts as $datecount)
    {
        fwrite($fh, $datecount.PHP_EOL);
    }
    flock($fh, LOCK_UN);
}
else
{
    //couldn't lock, might want to do stuff here
}
fclose($fh);

答案 1 :(得分:0)

希望这有助于你

<?php

$today = date('d/m/Y');
$dd=null;
$fp = fopen("test.txt", "r");
if ($fp) {
    while (($line = fgets($fp)) !== false) {
        $dd[] = explode(' ', $line);
    }
} else {

} 
fclose($fp);
$fw = fopen('test.txt', 'w');
if(is_array($dd) && count($dd) > 0){

foreach ($dd as $key => $value) {
    $cc = $value[1];
    if($today == $value[0])
    {
        $cc++;
    }
    fwrite($fw,$value[0].' '.$cc);
}

}else
{
    fwrite($fw,$today.' 0');
}
fclose($fw);

exit;
?>

我正在做的是,逐行读取文件数据并制作数组,然后再次写入,同一天计数将被分组

答案 2 :(得分:-1)

fwrite($ fp,date('d / m / Y')。''。$ count);