This question already has answers here:
Making email field required in php [closed]
(4 answers)
Closed 8 years ago.
I have this existing code and I am wondering how to make the name and email field required?
<?php
if(isset($_POST['submit'])){
$to = "xxx#email.com"; // this is your Email address
$from = $_POST['gift_email']; // this is the sender's Email address
$first_name = $_POST['gift_name'];
$subject = "Free Gift Request";
$msg = "A free gift has been requested from the following:"."\n";
$msg .= "Name: ".$_POST["gift_name"]."\n";
$msg .= "E-Mail: ".$_POST["gift_email"];
$headers = "From:" . $from;
mail($to,$subject,$msg,$headers);
//echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
header('Location:free_program_thankyou.php');
}
?>
For form
<input type="text" name="gift_email" required>
<input type="text" name="gift_name" required>
For Php
if(empty($_POST['gift_email']))
{
echo 'This field is required';
}else {
//Do what you want to do here
}
A two basic ways to do this:-
Within the php program check each required form field has been filled in send a new page with an error message back if it is not. Be sure to return the contents of any fields already filled in or your users will wish a plague of boils on your person.
Validate in javascript. Have a function triggered by the "onsubmit" condition which checks for all required forms fields are filled and highlights any that are not. see here
In practice a robust web site will do both. This seems like duplication however the javascript function is much more responsive and user friendly, BUT, the php server side validation cannot be gamed by turning JS off or spoofing responses.
Related
I am trying to troubleshoot this form. It is not sending reservation requests from the form on the website. Despite showing a message that the form was sent.
I tried editing email and the headers.
<?
//print_r($_POST);
$to = “email#emaildomain.com, {$posting['email']}";
function msg($text){
echo "
<script type='text/javascript'>
alert('".$text."');
top.location.href = 'http://www.aribbq.com';
</script>
";
exit;
}
function error($text){
echo "
<script type='text/javascript'>
alert('".$text."');
history.go(-1);
</script>
";
exit;
}
if (!$_POST[date]) {error('Please, insert Date.');}
if (!$_POST[time]) {error('Please, insert Time.');}
if (!$_POST[party]) {error('Please, insert Party.');}
if (!$_POST[reservation_name]) {error('Please, insert Name.');}
if (!$_POST[reservation_email]) {error('Please, insert Email.');}
if (!$_POST[reservation_phone]) {error('Please, insert Phone.');}
if(isset($_POST['submit'])){
// then send the form to your email
//$from = ('Reservation from AriBBQ.com'); // sender
$mailheaders = "From: contact#aribbq.com" . "\r\n"; // . "CC:
design#youremail.com"
$mailheaders .= 'Reply-To: ' . $posting['Email'] . "\r\n";
$subject = "AriBBQ.com Online Reservation";
$body = "\n Contact Name: ".$_POST[reservation_name]." \r\n\n";
//
$body .= " Email: ".$_POST[reservation_email]." \r\n\n"; //
$body .= " =================================================== \r\n\n"; //
$body .= " Book a table \r\n\n
Date: ".$_POST[date]." \r\n\n
Time: ".$_POST[time]." \r\n\n
Party: ".$_POST[party]." \r\n\n
Contact Details \r\n\n
Name: ".$_POST[reservation_name]." \r\n\n
Email: ".$_POST[reservation_email]." \r\n\n
Phone: ".$_POST[reservation_phone]." \r\n\n
Message: ".$_POST[reservation_message]." \r\n\n"; //
$body .= " =================================================== \r\n\n"; //
$result = mail($to , $from , $subject , $body , $mailheaders);
if($result) {msg('Thank you, your reservation has been sent. We
will send you a confirmation text or call in person.');} //
else{error('Sending mail is failed. Please try again');} //
} else {
error('No submitted. Please try again');
}
?>
You see the form online at http://aribbq.com/. Click on reservations. Once the email is received, we want to be able to reply to the sender's email address.
Alright, essentially, you need to turn on error reporting because your script threw about 20 errors at me which you would see with error reporting on. As my comment above said, add error_reporting(E_ALL); to the top of your script while you debug.
The issues I came across are as follows:
Parse error: syntax error, unexpected '#' in /mail.php on line 4 caused by an incorrect double quote character, not " but “. Subtle, but problematic.
Next up, Multiple or malformed newlines found in additional_header in /mail.php because as of PHP 5.5.2, a bug was fixed to prevent mail header injection, so all of your \n\n within the $mailheaders should be removed, I recommend appending PHP_EOL to the end of each line instead.
You have your $from variable included in the mail() call, this presents 2 issues. One, the mail() function does not have a from parameter, you include it within the headers. Two - your variable is actually commented out.
As I mentioned in the comment above, again, your email address variable to send to is typed as $posting['email']', and $posting['Email'] within $mailheaders. The problem here is $posting doesn't exist. Secondly, your form, which you should include the HTML for in future questions for self-contained examples for people to more easily help you (see https://stackoverflow.com/help/how-to-ask), doesn't post email at all, it posts reservation_email.
Finally, the majority of your $_POST references do not include quotes so PHP doesn't know what to do with the words in between the square brackets. $_POST[date] should be $_POST['date'], for example.
I've made all the above changes and managed to successfully email myself with the script and email form provided, the only thing that I didn't look at was your msg() which didn't show me a success message. I did, however, put an echo statement before this function call which printed out fine.
I hope this helps you get your script up and running, good luck and remember, error_reporting(); is your friend!
I have a form. I'm using "post" method that sends and emails to multiple people that registered. Then the $body of the email is based on a template. No database, no classes, simple form. Yes I read up about this already they're all there I just couldn't put it together, related to this case.
The text "email_template.txt" should have something like:
Hello #firstname# #lastname#. Thank you for registering! Your registered email is #email#
Would look like this upon processing by PHP
Hello **John Doe**. Thank you registering! Your registered email is **example#example.com**.
On my php I have something like:
<?php
//form and validation
$firstname = "John"; // inputed name on the form, let say
$lastname = "Doe"; // inputed last name
$email = "example"; // inputed email
//email message
$body = ... some type of a get_file_content....
mail($_POST['email'], 'Party Invitation', $body, 'From: admin#admin.com');
?>
Where $body is the email message to the registrants submitted via this PHP form.
sprintf will work good
your template could be:
Hello %s %s. Thank you for registering! Your registered email is %s
$body = sprintf($fileContents,$firstname,$lastname,$email);
or str_replace(), pretty much a find replace.
$body = "Hello #firstname# #lastname#. Thank you for registering! Your registered email is #email#";
$body = str_replace("#firstname#",$firstname,$body);
$body = str_replace("#lastname#",$lastname,$body);
$body = str_replace("#email#",$email,$body);
I hope I'm missing something pretty basic here but: An empty form is getting submitted randomly, sometimes 3-8 times a day, then none for a few days and so on.
The empty submits always email with the subject as "[Website Contact Form]." Even though there is no validation in my php, in the html code the subject is chosen from a drop-down menu with the default as "General Enquiry." Notice in the php code below, there is no way for a human to submit an empty form with the above subject line, that is, it would always be "[Website Contact Form]General Enquiry" if I press submit without entering anything.
I have contact.html call this contact.php file:
<?
$email = 'info#mail.com';
$mailadd = $_POST['email'];
$headers = 'From: ' . $_POST['email'] . "\r\n";
$name = $_POST['name'];
$subject = '[Website Contact Form] ' . $_POST['subject'];
$message = 'Message sent from: ' . $name . '. Email: ' . $mailadd . '. Organization: ' . $_POST['company'] . '. Phone: ' . $_POST['phone'] . '. ';
$message .= 'Message: ';
$message .= $_POST['message'];
if (mail($email,$subject,$message, $headers)) {
echo "<p>Thank You! We'll get back to you shortly.</p>";
}
else {
echo "<p>Error...</p>";
}
?>
I use this code for many websites, but have never encountered this issue. Is there something so obviously wrong with this code that I'm missing? Any help would be greatly appreciated!
I suspect that you may not be checking that these variables are set before you send the email. Someone requesting contact.php directly (without any form data) may produce the results you have described. If this is the case, the following code should work like a charm:
<?php
if (isset($_POST['submit']) {
// form code
}
else {
// The form was not submitted, do nothing
}
?>
Even if that's not that case, such a simple check is always good practice.
Furthermore, you should always validate any user input just as a good habit. You don't want your server flooding your inbox with emails. I suggest using regexs to validate the input provided and possibly use a captcha service (such as ReCaptcha).
If you've been using this code and it's been working fine then I'd check what variables you changed with this case for example your submit form.
Try out your form with all common possibilities and see if it works. And empty Subject will give your form the subject "[Website Contact Form]". Check that your script actually get's the post variables and your form submits the right variables. Your dropdown might have an option with value of "" and the innerHTML "General Enquiry". The value is what will get submitted.
It's good to check inputs server-side as well
<?php
if(isset($_POST['subject'],$_POST['email'])){
}
?>
A client recently got a spam warning from their host.
I think I have pin pointed the issue to an old contact us form. Simple html on the front end and a simple PHP script on the back end.
if ($_POST['submit'] == "Send"){
//START SEND MAIL SCRIPT
$mail = $_POST['email'];
$to = "me#gmail.com";
$subject = "Message from Website Contact Us Form";
$headers = "From: Contact us Form <webmaster#website.co.uk>";
$message = "Message from Contact Us Form\n\n";
$message .= "\nName: " . $_POST['contactname'];
$message .= "\nEmail: " . $_POST['contactemail'];
$message .= "\nTelephone: " . $_POST['contactphone'];
$message .= "\n\n\nMessage:\n" . $_POST['contactmessage'];
if(mail($to,$subject,$message,$headers)) {
header('Location: http://www.website.co.uk/contact-us/?action=success');
}else{
header('Location: http://www.webisite.co.uk/contact-us/?action=fail');
}//END IF MAIL
}//END SCRIPT
I know the remedies to fix it such as sanitizing post vars properly, using captchas, using a hidden 'honeypot' blank field, js tricks etc etc (I also like the look of this script too http://www.alt-php-faq.com/local/115/)
But to help me understand what was going on I want to know how this script is being manipulated. A foreign script posting vars to it but how do they send email to anyone apart from
'me#gmail.com' or if they are forcing cc / bcc fields somehow why do I not get all spam as well??
Thanks
Line like this $message .= "\nName: " . $_POST['contactname']; can be dangerous.
If $_POST['contactname']='MegaSteve4 \r\nCc: email1#mail.com, email2#mail.com'; are set, 2 uses will get spam mail.
See carefully. Its appending more headers. In this case Cc. I am not sure if Cc is a raw email header. But I hope you get the idea.
You're not doing any escaping of the post data. That means that this form is vulnerable to injection attacks.
I couldn't tell you how they did it, but that's probably what happened.
I am looking for a means of implementing a "Contact Us" routine/page that I can apply to my site that is purely a HTML website only.
I am assuming this will need to be a PHP process to send emails from a Contact Us form, but I am unsure how to do it.
Since you're pure HTML now, I'm assuming you're trying to keep this simple?
Use a service.
As you said you were interested in looking into PHP, you could do this with one script (say, for example, Contact.php). In your Contact.php file you would put a simple HTML form with room for name, email address, short message, etc. This form can just submit the form data to the same page, process the data, and send out an email with PHP's mail() function. Doing it this way avoids the need to display your email address to the world.
Something simple like the following should get you started, although you are going to want to check any and all user input before mailing it to yourself!
<html>
<body>
<?php
// if the form was filled out and submitted, mail it
if ( isset($_REQUEST['subButton']) )
{
$email = $_REQUEST['email'] ;
$subject = "Contact Us request from site";
$message = $_REQUEST['message'] ;
mail( "secretEmailAddress#email.com", "Subject: $subject", $message, "From: $email" );
header("location: contact.html");
}
else
{
echo "<form method='post' action='Contact.php'>
Email: <input name='email' type='text'/><br/>
Message:<br/>
<textarea name='message' rows='10' cols='30'>
</textarea><br/>
<input type='submit' name='subButton' value='Contact Us'/>
</form>";
}
?>
</body>
</html>
The easiest way is to just use a mailto: link.
Contact Us
Mailto links are very insecure. expect to get spam up the wazoo.
Instead use javascript to simply mask it.
Put this where you want the link to be setup
var mailE1 = "contact";
var mailE2 = "yoursite.com";
var linktext = "Email Us";
document.write("" + linktext + "")