PHP and contact form

I am having trouble setting up the php script correctly for my contact form. I was able to send it via email, but the email does not display name, email or text.

PHP script

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'myemail@email.comm';
$subject = 'Hello';

mail ($to, $subject, $message, "From: " . $name);
echo "Your Message has been sent.";
?>

      

contact form

<form role="form" action="contact.php">
<div class="form-group">
<label for="InputName">Name</label>
<input name="name" type="text" class="form-control" id="InputName" placeholder="Enter Name">
</div>

<div class="form-group">
<label for="InputEmail">Email Address</label>
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter email">
</div>

<div class="form-group">
<label for="InputText">Message</label>
<input name="message" type="text" class="form-control" id="InputText" placeholder="Enter Text">
</div>

<button name="submit" type="submit" class="btn btn-default">Send</button>
</form>

      

+3


source to share


3 answers


You are using POST variables, but your form is as follows:

<form role="form" action="contact.php">

      

no POST method set. The default form is GET when no method is defined.

Therefore, you will need to change the form to

<form role="form" action="contact.php" method="post">

      


From the comment you left:

"I still have a problem where, instead of giving me the email they enter, it gives me an email address generated by the hosting company that doesn't work."

A: Most likely due to the way you use From:

in your code which is the person's name. The mail is expecting an email address.

Replace:

mail ($to, $subject, $message, "From: " . $name);

      

from:



mail ($to, $subject, $message, $header);

      

and adding the following to $subject = 'Hello';

$header = "From: ". $name . " <" . $email . ">\r\n";

      

This way you will see the person's name in the email with a valid "From" header.


Additional Notes:

I also suggest you check if any of the fields are left using:

if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']))
{
    // execute code
}

      

Otherwise, anyone can send email without any information.

You can also add else{}

to it likeelse { echo "Please fill in all the fields."; }

  • This is a very simple method.
+9


source


Your form needs an attribute

method="POST"

      



Without this, the browser has a default method="GET"

that submits the form to a url likehttp://example.com/default.php?name=First%20Last&email=...

+1


source


You must specify the POST method:

<form role="form" method="POST" action="contact.php">

      

+1


source







All Articles