LoginSignup
9
11

More than 3 years have passed since last update.

PHP ログイン・ログアウト機能

Last updated at Posted at 2020-05-01

フルスクラッチPHPでのログイン機能のやり方

DBとの連携でのシンプルなログイン、ログアウト
事前にMySQLにユーザー名とログイン用のメールアドレスとパスワードは登録済み
セキュリティー対策は無し

login_form.php
<?php
session_start();
?>

<!DOCTYPE html>
<html>
<head>
<LINK rel="stylesheet" href="index.css">
<title>ログイン入力</title>
</head>
<body>
<h1>
<font size='5'>ログインページ</font>
</h1>

<?php if (isset($_SESSION['id'])) : ?>

<p>
<font size='5'>ようこそ</font>
</p>
<p><?php echo $_SESSION['name']; ?>さん</p>
<p><a href='logout.php'>ログアウト</a></p>

<?php else : ?>

<form action='login.php' method='post'>
<p>メールアドレス</p>
<input type='text' name='mail'>
<p>パスワード</p>
<input type='text' name='pass'>
</br>
<input class="btn" type='submit' value='ログイン'>
</form>

<?php endif; ?>

</body>
</html>
index.css
input {
  width: 200px;
  padding: 5px;
  font-size: 18px;
  border: 2px solid #a9a9a9; 
}

.btn{
    background-color: #a9a9a9;
    margin-top: 30px;
    width: 210px;
    padding: 5px;
    border-radius: 3px;
    transition: .3s ease-out;
  }

シンプルなログインフォームの完成

スクリーンショット 2020-05-01 16.26.46.png

login.php
<?php
session_start();
$mysql    = 'mysql:host=localhost;dbname=データベース名;charset=utf8';
$user     = 'ユーザー名';
$passwoad = 'パスワード';

$mail = $_POST['mail'];
$pass = $_POST['pass'];

if (empty($mail) || empty($pass)) {
    $output = '入力してください';
} else {
    try {
        $db     = new PDO($mysql, $user, $passwoad);
        $select = "SELECT * FROM members WHERE mail = '$mail' AND pass = '$pass'";
        $res    = $db->query($select);
        $res->execute();
    } catch (PDOException $e) {
        echo '接続エラー: ' . $e->getMessage();
    }
    if ($res->rowCount() < 1) {
        $output = 'ログインできませんでした';
    } else {
        $row = $res->fetch();
        $_SESSION['id']   = $row['id'];
        $_SESSION['name'] = $row['name'];
        $_SESSION['mail'] = $row['mail'];
        $output = 'ログインできました';
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>ログイン</title>
</head>
<body>
<h1>
<font size='5'>ログイン情報確認</font>
</h1>
<p><?php echo $output; ?></p>

<?php if (!isset($_SESSION['name'])) : ?>

<p><a href='login_form.php'>ログインページへ戻る</a></p>

<?php endif; ?>

</body>
</html>

入力に不備があると

スクリーンショット 2020-05-01 16.29.07.png

データベースに登録しているメールアドレス、パスワードが一致した場合

スクリーンショット 2020-05-01 16.27.28.png

ログインページに再び戻ると

スクリーンショット 2020-05-01 16.27.56.png

logout.php
<?php
session_start();
$_SESSION = array();
session_destroy();
?>

<!DOCTYPE html>
<html>
<head>
<title>ログアウト</title>
</head>
<body>
<h1>
<font size='5'>ログアウトしました</font>
</h1>
<p><a href='login_form.php'>ログインページに戻る</a></p>
</body>
</html>

ログアウトを押すと

スクリーンショット 2020-05-01 16.28.04.png

9
11
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
9
11