LoginSignup
0
0

More than 3 years have passed since last update.

PHPでお手軽カウンター

Last updated at Posted at 2019-04-14

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

functions.php

<?php

function counter(){

  //日付を取得
  $base_day = date("Y/m/d");

  //IPアドレス取得
  $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;
  }
  //IPアドレスが一致してなかったら(連続カウント防止)
  if ($remoteAddr!=$reg_remoteAddr) {

    //合計と今日のカウントを1増やす
    $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と同じ位置に配置させる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0