0
0

PHP+MySQLでユーザーログインシステムを作成(覚書)

Posted at

PHPでユーザーログインシステムを作成するための備忘録

データベースにユーザー情報を保存します。
ユーザー名とパスワードを使用し、ログイン認証を行いセッションを使用してログイン状態を管理します。

データベースのセットアップ

ユーザー情報を保存するテーブルを作成します。

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL
);

login.php|PHPファイルの作成

ログインページ、ログインフォームの作成をします。

<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    $password = $_POST["password"];

    // データベースからユーザー情報を取得
    // この部分はデータベースへの接続とクエリの実行が必要です

    if ($user_exists && password_verify($password, $hashed_password)) {
        // 認証成功
        $_SESSION["username"] = $username;
        header("Location: dashboard.php"); // ダッシュボードページにリダイレクト
        exit;
    } else {
        // 認証失敗
        $error_message = "ユーザー名またはパスワードが正しくありません。";
    }
}
?>

表示部分のHTMLは以下、別ファイルにしてincludeしても良いし、login.phpに処理と一緒に書いてもOK。

<!DOCTYPE html>
<html>
<head>
    <title>ログイン</title>
</head>
<body>
    <h1>ログイン</h1>
    <?php if (isset($error_message)) { ?>
        <p><?php echo $error_message; ?></p>
    <?php } ?>
    <form method="POST" action="">
        <label for="username">ユーザー名:</label>
        <input type="text" name="username" required><br>
        <label for="password">パスワード:</label>
        <input type="password" name="password" required><br>
        <button type="submit">ログイン</button>
    </form>
</body>
</html>

簡易的に書いた覚書です。
動作確認してないのでエラー出るかも。

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