1
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?

ThinkPHPで簡単ログイン・登録APIを作ってみた【TP6対応】

1
Posted at

皆さん、こんにちは。

今回は「ThinkPHPで簡単ログイン・登録APIを作ってみた【TP6対応】」について紹介させていただきます。

PHPの軽量フレームワーク「ThinkPHP 6」を使って、ログインユーザー登録のAPIを実装してみたので、メモがてら記事に残しておきます。

🧱 使用技術

  • フレームワーク: ThinkPHP 6.x
  • データベース: MySQL
  • PHPバージョン: 8.x 推奨

📁 ディレクトリ構成(抜粋)

app/
├── controller/
│ └── Auth.php ← ログイン・登録処理
├── model/
│ └── User.php ← ユーザーモデル
route/
└── app.php ← ルーティング定義

🛠️ usersテーブルの作成

まずはユーザー情報を保存するためのテーブルを作成しておきます。

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

API開発

👤 Userモデルの作成

// app/model/User.php

namespace app\model;

use think\Model;

class User extends Model
{
    protected $table = 'users';
    protected $hidden = ['password']; // レスポンスでパスワードを非表示
}

🔐 Authコントローラー

📌 ユーザー登録API(POST /api/register)

// app/controller/Auth.php

public function register(\think\Request $request)
{
    $data = $request->post();

    if (empty($data['username']) || empty($data['password'])) {
        return json(['error' => 'Username and password required'], 400);
    }

    if (\app\model\User::where('username', $data['username'])->find()) {
        return json(['error' => 'Username already exists'], 409);
    }

    $user = new \app\model\User();
    $user->username = $data['username'];
    $user->password = password_hash($data['password'], PASSWORD_DEFAULT);
    $user->save();

    return json(['message' => 'Registration successful']);
}

📌 ログインAPI(POST /api/login)

public function login(\think\Request $request)
{
    $data = $request->post();

    $user = \app\model\User::where('username', $data['username'])->find();

    if (!$user || !password_verify($data['password'], $user->password)) {
        return json(['error' => 'Invalid credentials'], 401);
    }

    return json(['message' => 'Login successful', 'user' => $user]);
}

🔧 ルーティング設定

// route/app.php

use think\facade\Route;

Route::post('api/register', 'auth/register');
Route::post('api/login', 'auth/login');

🧪 Postmanでテスト

✅ 登録リクエスト

POST /api/register
Content-Type: application/json

{
  "username": "testuser",
  "password": "secret"
}

✅ ログインリクエスト

POST /api/login
Content-Type: application/json

{
  "username": "testuser",
  "password": "secret"
}

セキュリティ補足

  • password_hash() / password_verify() を使って安全にパスワード管理
  • ユーザー名の重複チェックあり
  • 実運用では JWTトークン や ミドルウェアによる保護 など追加がおすすめ

ThinkPHPは中国国内で広く使われているだけあって、意外と使いやすくて高速です。Laravelほど学習コストは高くなく、API開発にも向いています。

この記事が、ThinkPHPでAPIを作りたい方の参考になれば嬉しいです🙌
もし「JWT対応版」や「ミドルウェアで保護したい」といった要望があれば、ぜひコメントください!

今日は以上です。

ありがとうございました。
よろしくお願いいたします。

1
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
1
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?