Skip to content

Instantly share code, notes, and snippets.

@codeforfun-jp
Created October 26, 2023 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeforfun-jp/1b4ddddec957c1000f13676c97b734e9 to your computer and use it in GitHub Desktop.
Save codeforfun-jp/1b4ddddec957c1000f13676c97b734e9 to your computer and use it in GitHub Desktop.
PHP Contact Form - 3
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
// POSTでのアクセスでない場合
$name = '';
$email = '';
$subject = '';
$message = '';
$err_msg = '';
$complete_msg = '';
} else {
// フォームがサブミットされた場合(POST処理)
// 入力された値を取得する
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// エラーメッセージ・完了メッセージの用意
$err_msg = '';
$complete_msg = '';
// 空チェック
if ($name == '' || $email == '' || $subject == '' || $message == '') {
$err_msg = '全ての項目を入力してください。';
}
// エラーなし(全ての項目が入力されている)
if ($err_msg == '') {
$to = 'admin@test.com'; // 管理者のメールアドレスなど送信先を指定
$headers = "From: " . $email . "\r\n";
// 本文の最後に名前を追加
$message .= "\r\n\r\n" . $name;
// メール送信
mb_send_mail($to, $subject, $message, $headers);
// 完了メッセージ
$complete_msg = '送信されました!';
// 全てクリア
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html lang="jp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>お問い合わせフォーム</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body class="bg-light">
<div class="container mt-5 pt-5">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3 class="mb-5 text-center">お問い合わせ</h3>
<?php if ($err_msg != ''): ?>
<div class="alert alert-danger">
<?php echo $err_msg; ?>
</div>
<?php endif; ?>
<?php if ($complete_msg != ''): ?>
<div class="alert alert-success">
<?php echo $complete_msg; ?>
</div>
<?php endif; ?>
<form method="post">
<div class="mb-3">
<input type="text" class="form-control" name="name" placeholder="お名前" value="<?= $name; ?>">
</div>
<div class="mb-3">
<input type="text" class="form-control" name="email" placeholder="メールアドレス" value="<?= $email; ?>">
</div>
<div class="mb-3">
<input type="text" class="form-control" name="subject" placeholder="件名" value="<?= $subject; ?>">
</div>
<div class="mb-5">
<textarea class="form-control" name="message" rows="5" placeholder="本文"><?= $message; ?></textarea>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-success">送信</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment