2
3

More than 3 years have passed since last update.

PHP ひとこと掲示板

Last updated at Posted at 2020-08-12
<?php

$filename = './bbs.txt';
$date  = date('Y-m-d H:i:s');
$data  = [];
$error = [];
$username = '';
$comment   = '';

if($_SERVER['REQUEST_METHOD'] === 'POST'){

    if (isset($_POST['username']) === true) {
        $username = trim($_POST['username']);
    }
    if (isset($_POST['comment']) === true) {
        $comment = trim($_POST['comment']);
    }

    if ($username === '') {
        $error[] = '名前を入力してください';
    } else if (mb_strlen($username) > 20 ) {
        $error[] = '名前は20文字以内で発言してください';
    }
    if ($comment === '') {
        $error[] = 'ひとことを入力してください';
    } else if (mb_strlen($comment) > 100) {
        $error[] = 'ひとことは100文字までで発言してください';
    }

    if (count($error) === 0) {
        $log = $username . ":\t" . $comment . "\t-" . $date . "\n";
        if (($fp = fopen($filename, 'a')) !== FALSE) {       
            if (fwrite($fp, $log) === FALSE) {              
                $error[] =  'ファイル書き込み失敗:  ' . $filename;
            }
            fclose($fp);
        }
    }
}


if(is_readable($filename) === true){
    if(($fp = fopen($filename,'r')) !== false){
        while(($tmp = fgets($fp)) !== false){
            $data[] = htmlspecialchars($tmp,ENT_QUOTES,'UTF-8');
        }
    }
} else {
    $error[] = 'ファイルがありません';
}

$data = array_reverse($data);

?>
<!doctype html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>ひとこと掲示板</title>
    </head>
    <body>
        <h1>ひとこと掲示板</h1>
<?php if (count($error) > 0) { ?>
    <ul>
    <?php foreach($error as $value) { ?>
        <li><?php print $value; ?></li>
    <?php } ?>
    </ul>
<?php } ?>
        <form method="post">
            名前:<input type="text" name="username">
            ひとこと:<input type="text" name="comment">
            <input type="submit" value="送信">
        </form>
        <ul>
<?php foreach ($data as $value) { ?>
            <li><?php print $value; ?></li>
<?php } ?>
        </ul>
    </body>
</html>

countを便利に使う。

2
3
1

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
2
3