0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

中古ノート、買ってみた。 その12

Posted at

概要

中古ノート買ってみた。
wsl1、入れてみた。
ubuntu18.04 、入れてみた。
apache2,php,sqlite、入れてみた。
phpフレームワーク、cheetanを見つけたので、copilotに聞いてみた。

参考にしたページ

回答

「ちいたん (cheetan)」は、PHPで書かれた非常に軽量なWebアプリケーションフレームワークです。Bottle(Python)に似た思想で、1ファイルで完結するシンプルな構成が特徴です。

以下は、cheetanを使った基本的なサンプルコードです。cheetan.phpを同じディレクトリに置いて、簡単なルーティングとDBアクセスを試す例です。


? サンプルコード:Hello World + SQLite3アクセス

<?php
require_once('cheetan.php');

function action_index($c) {
    return 'Hello, Cheetan!';
}

function action_dbtest($c) {
    // SQLite3 DBに接続(事前にtest.dbを作成しておく)
    $c->load('db');
    $c->db->connect('sqlite:test.db');

    // テーブル作成(初回のみ)
    $c->db->query("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, text TEXT)");

    // データ挿入
    $c->db->query("INSERT INTO messages (text) VALUES ('こんにちは、ちいたん!')");

    // データ取得
    $rows = $c->db->getall("SELECT * FROM messages");

    // 表示
    $output = "<ul>";
    foreach ($rows as $row) {
        $output .= "<li>" . htmlspecialchars($row['text']) . "</li>";
    }
    $output .= "</ul>";
    return $output;
}

? 実行方法

  1. cheetan.phpGitHubのリポジトリから取得
  2. 上記コードを index.php として保存
  3. test.db を空で作成(SQLite3)
  4. PHPのビルトインサーバーで起動
    php -S localhost:8000
    
  5. ブラウザでアクセス
    • http://localhost:8000/ → Hello, Cheetan!
    • http://localhost:8000/dbtest → DBからのメッセージ一覧

もっと複雑なルーティングやテンプレート処理も可能です。興味があれば、次はフォーム送信やJSON APIのサンプルも作れますよ。どんな機能を試してみたいですか?

もちろんです!以下は、cheetan を使ったシンプルなフォーム送信のサンプルです。ユーザーが名前を入力して送信すると、サーバー側で受け取って表示する例です。


? index.php(フォーム表示と送信処理)

<?php
require_once('cheetan.php');

function action_index($c) {
    // フォーム表示
    return '
        <form method="post" action="/submit">
            名前: <input type="text" name="name">
            <input type="submit" value="送信">
        </form>
    ';
}

function action_submit($c) {
    // POSTデータ取得
    $name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '未入力';

    // 結果表示
    return "こんにちは、{$name} さん!フォーム送信ありがとうございます。";
}

? 実行手順

  1. cheetan.php を同じディレクトリに配置
  2. 上記コードを index.php に保存
  3. PHPビルトインサーバーで起動
    php -S localhost:8000
    
  4. ブラウザでアクセス
    • http://localhost:8000/ → フォーム表示
    • 名前を入力して送信 → http://localhost:8000/submit に結果表示

?補足

  • action_ルート名 という関数がルーティングの役割を果たします。
  • $_POST でフォームデータを受け取り、htmlspecialchars() でXSS対策しています。
  • DB保存やバリデーションを追加することも可能です。

次は、データベースに保存するフォームや、バリデーション付きのフォームも作れます。どこまで拡張したいですか?

了解です!以下は、cheetan を使って JSON API を構築するシンプルなサンプルです。クライアントが /api/greet にアクセスすると、JSON形式で挨拶メッセージを返します。


? index.php(JSON APIエンドポイント)

<?php
require_once('cheetan.php');

// JSON APIエンドポイント
function action_api_greet($c) {
    // ヘッダー設定(JSONとして返す)
    header('Content-Type: application/json; charset=utf-8');

    // パラメータ取得(GETまたはPOST)
    $name = isset($_REQUEST['name']) ? $_REQUEST['name'] : 'ゲスト';

    // レスポンスデータ
    $response = [
        'message' => "こんにちは、{$name} さん!",
        'timestamp' => date('Y-m-d H:i:s'),
    ];

    // JSON出力
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

? 実行方法

  1. cheetan.php を同じディレクトリに配置
  2. 上記コードを index.php に保存
  3. PHPビルトインサーバーで起動
    php -S localhost:8000
    
  4. ブラウザまたは curl でアクセス
    • http://localhost:8000/api/greet?name=太郎
    • または
      curl "http://localhost:8000/api/greet?name=太郎"
      

? レスポンス例

{
  "message": "こんにちは、太郎 さん!",
  "timestamp": "2025-09-14 11:12:00"
}

?応用ポイント

  • $_REQUEST で GET/POST 両方対応
  • JSON_UNESCAPED_UNICODE で日本語をそのまま出力
  • header() で Content-Type を明示

DB連携や認証付きAPIも可能です。次はデータベースからJSONで一覧を返すAPIを作ってみましょうか?それともPOSTでデータ登録するAPIに進みますか?

了解です!以下は、cheetan + SQLite3 を使って POST されたフォームデータをデータベースに登録するサンプルです。ユーザーが名前とメッセージを送信すると、それを SQLite に保存します。


? index.php(フォーム表示 + POST登録 + 一覧表示)

<?php
require_once('cheetan.php');

function action_index($c) {
    return '
        <form method="post" action="/submit">
            名前: <input type="text" name="name"><br>
            メッセージ: <input type="text" name="message"><br>
            <input type="submit" value="送信">
        </form>
    ';
}

function action_submit($c) {
    $name = isset($_POST['name']) ? $_POST['name'] : '';
    $message = isset($_POST['message']) ? $_POST['message'] : '';

    // DBロード
    $c->load('db');
    $c->db->connect('sqlite:messages.db');

    // テーブル作成(初回のみ)
    $c->db->query("CREATE TABLE IF NOT EXISTS messages (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        message TEXT,
        created_at TEXT
    )");

    // データ登録
    $stmt = $c->db->prepare("INSERT INTO messages (name, message, created_at) VALUES (?, ?, ?)");
    $stmt->execute([$name, $message, date('Y-m-d H:i:s')]);

    // 登録完了メッセージ
    return "登録しました!<br><a href=\"/list\">一覧を見る</a>";
}

function action_list($c) {
    $c->load('db');
    $c->db->connect('sqlite:messages.db');

    $rows = $c->db->getall("SELECT * FROM messages ORDER BY id DESC");

    $html = "<h2>投稿一覧</h2><ul>";
    foreach ($rows as $row) {
        $html .= "<li><strong>" . htmlspecialchars($row['name']) . "</strong>: " . htmlspecialchars($row['message']) . " <em>(" . $row['created_at'] . ")</em></li>";
    }
    $html .= "</ul><a href=\"/\">戻る</a>";
    return $html;
}

? 実行手順

  1. cheetan.php を同じディレクトリに配置
  2. 上記コードを index.php に保存
  3. 空の SQLite DBファイルは不要(自動生成されます)
  4. PHPビルトインサーバーで起動
    php -S localhost:8000
    
  5. ブラウザでアクセス
    • http://localhost:8000/ → フォーム表示
    • 送信 → /submit で登録
    • /list → 登録されたメッセージ一覧表示

?ポイント

  • prepare() + execute() で安全なSQL実行(SQLインジェクション対策)
  • htmlspecialchars() でXSS対策
  • SQLiteはファイルベースなので、手軽に使えます

次は、JSON APIでこの一覧を返すようにしたり、バリデーションやエラーハンドリングを追加することもできますよ。どこまで拡張してみましょう?

以上。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?