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>
source to share
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.
- For more information on message headers visit http://php.net/manual/en/function.mail.php .
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.
source to share