Edited at

PHPでお手軽カウンター

こんな感じでファイルを作る。


functions.php


<?php

function counter(){
$keta = 5;
$base_day = date("Y/m/d");
$remoteAddr = $_SERVER['REMOTE_ADDR'];
$filepath = "count.dat";
$fp = fopen($filepath,"r+b");
flock ($fp,LOCK_EX);
$line = fgets($fp);
list($reg_day, $total, $today, $yesterday, $reg_remoteAddr) = explode(",", $line);

if ($base_day != $reg_day){
$yesterday = $today;
$today = 0;
}

if ($remoteAddr!=$reg_remoteAddr) {
$total++;
$today++;
ftruncate($fp,0);
rewind($fp);
fwrite($fp,"$base_day,$total,$today,$yesterday,$remoteAddr");
fclose($fp);
}

echo "今日{$today}&nbsp;";
echo "昨日{$yesterday}&nbsp;";
echo "合計{$total}";
}


カウンターを表示させたい場所で実行。


index.php

<?php

include("functions.php");
counter();
?>

「count.dat」の空ファイルを作り、functions.phpと同じ位置に配置させる。