php簡易掲示板

投稿内容はdatファイルに格納します。

<?php

$dataFile = 'bbs.dat';

// csrf
session_start();

function setToken(){
  $token = sha1(uniqid(mt_rand(), true));
  $_SESSION&#91;'token'&#93; = $token;
}
function checkToken(){
  if (empty($_SESSION&#91;'token'&#93;) || ($_SESSION&#91;'token'&#93; !=$_POST&#91;'token'&#93;)){
    echo "不正なpostが行われました!";
    exit;
  }
}

function h($s){
  return htmlspecialchars($s, ENT_QUOTES, 'utf-8');
}

if($_SERVER&#91;'REQUEST_METHOD'&#93; == 'POST' &&
  isset($_POST&#91;'message'&#93;) &&
  isset($_POST&#91;'user'&#93;)){
    checkToken();

  $message =trim($_POST&#91;'message'&#93;);
  $user = trim($_POST&#91;'user'&#93;);

 if($message !== ''){

   $user = ($user === '') ? 'ななしさん' : $user;

   $message = str_replace("\t", '', $message);
   $user = str_replace("\t", '', $user);
   $postedAt = date('Y-m-d H:i:s');

  $newData = $message . "\t" . $user . "\t" . $postedAt. "\n";

  $fp = fopen($dataFile, 'a');
  fwrite($fp, $newData);
  fclose($fp);
   }
} else {
  setToken();
}

$posts = file($dataFile, FILE_IGNORE_NEW_LINES);

$posts = array_reverse($posts);
?>
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>簡易掲示板</title>
</head>
<body>
  <h1>簡易掲示板</h1>
  <form action="" method="post">
    message: <input type="text" name="message">
    user: <input type="text" name="user">
    <input type="submit" value="投稿">
    <input type="hidden" name="token" value="<?php echo h($_SESSION&#91;'token'&#93;); ?>">
  </form>
  <h2>投稿一覧(<?php echo count($posts); ?>件)</h2>
  <ul>
    <?php if (count($posts)) : ?>
      <?php foreach ($posts as $post) : ?>
        <?php list($message, $user, $postedAt) =  explode("\t", $post); ?>
        <li><?php echo h($message); ?>(<?php echo h($user); ?>)-<?php echo h($postedAt); ?></li>
      <?php endforeach; ?>
       <li></li>
    <?php else : ?>
    <li>まだ投稿はありません。</li>
  <?php endif; ?>
  </ul>
</body>
</html>

%e7%84%a1%e9%a1%8c