1

最近 PHP を学び始めましたが、お問い合わせフォームに問題があります。

フォームの問題は、メールが送信されず、フォームを送信する前にフォームの下にエラー メッセージが表示されることです。時々私はそれを機能させますが、それから再び壊れます。

また、「メッセージを送信しました!」というメッセージをお願いします。送信時に連絡先フォーム全体を置き換える。別のページにリンクせずにそれを実現するにはどうすればよいですか?

コードは次のとおりです。

<form method="POST" action="index.php">
    <input name="name" type="text" placeholder="Name">
    <input name="email" type="email" required placeholder="Email">
    <input name="subject" type="text" placeholder="Subject">
    <textarea name="message" rows="15" required placeholder="Message"></textarea>
    <input name="submit" type="submit" value="Send">
</form>

<?php
    if(isset($_POST['submit'])) 
    {
    $name_field=$_POST['name'];
    $email_field=$_POST['email'];
    $subject_field=$_POST['subject'];
    $message_field=$_POST['message'];
    $to="example@outlook.com";
    $from="example@outlook.com";
    $subject="Contact Form Message";
    $body="Name: $name_field\n Email: $email_field\n Subject: $subject_field\n Message:\n $message_field";
    mail($to,$subject,$body,$from);
    echo "<p>Message sent!</p>"; 
    } 
    else
    {
    echo "<p>An error occured. Please try again.</p>";
    }
?>

何卒よろしくお願いいたします。また、コードをより良く、よりクリーンに、またはより効率的にする方法があれば教えてください。

4

2 に答える 2

1

You haven't said what doesn't work, but to not display the form if it has been submitted, you want to move your form into the php, and only print it if the form hasn't been submitted.

Also for some further reading to help you out, there are very nice video tutorials here, this one is specifically on making a contact form :-D http://thenewboston.org/watch.php?cat=11&number=100

You also appear to be echoing the error message if the form hasn't been submitted, so one first load you would get the error. And your mail command doesn't looks right.

<?php

//if the form hasn't been submitted yet, print the form.
if (!isset($_POST['submit'])){
print <<<END
<form method="POST" action="index.php">
  <input name="name" type="text" placeholder="Name">
  <input name="email" type="email" required placeholder="Email">
  <input name="subject" type="text" placeholder="Subject">
  <textarea name="message" rows="15" required placeholder="Message"></textarea>
  <input name="submit" type="submit" value="Send">
</form>
END;
}

//if the form has been submitted.
if(isset($_POST['submit'])) 
{
$name_field=$_POST['name'];
$email_field=$_POST['email'];
$subject_field=$_POST['subject'];
$message_field=$_POST['message'];
$to="example@outlook.com";
$subject="Contact Form Message";
$body="Name: $name_field\n Email: $email_field\n Subject: $subject_field\n Message:\n $message_field";
$headers = "From: example@outlook.com";

  if(!mail($to,$subject,$body,$headers)){
      echo 'failed !!';
  }
  else{
      echo "<p>Message sent!</p>"; 
  }
} 
于 2013-09-10T18:03:59.243 に答える