Hello Fellow Stackers,
New to PHP and I am putting together a multipage form from pre-built code.
Basically the user selects as many checkboxes as they want... then the form submits to this secondary page. This secondary page echo's the checkboxes they chose at the top of the page via $check.. then they can enter their contact information and all of the information gets submitted via form, along with the $check information.
Everything is working perfectly except $check isn't being entered into the form message, but it works up at the top of the page, displaying which options the user inputted.
Any help is appreciated!
<?php
$emailOut = '';
if(!empty($_POST['choices'])) {
foreach($_POST['choices'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
$emailOut .= $check."\n"; //any output you want
}
}
$errors = '';
$myemail = 'test#myemailHERE.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. $check ".
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message \n $emailOut";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
The thing in this situation is that when you get down to the email, $check is the last option displayed. You need to use the foreach statment to build the array or email output such as
$emailOut = "";
foreach($_POST['choices'] as $check) {
$emailOut .= $check."\n"; //any output you want
}
Then use your email variable in the same way
$email_body = "You have received a new message. Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message \n $emailOut";
UPDATE
From further investigation and more code submitted, it appears that you are working with a multi-form submssion issue. The issue is you have form 1 (checkboxes) that submits to form 2 (email).
Since when doing the checks after the checkbox submission, no name, email, etc was given so $errors were given and no email sent. When filling out the email form, the checkboxes were not sent again so $check or even $_POST['choices'] had values.
You can either put the two forms into one, or you can look into a way to save the values by passing them and filling a 'hidden' field (<input type='hidden' value='...'>) or use a session with PHP.
Related
I currently have a contact form, from which e-mails are composed and sent using php. I use a separate php file for that.
$errors = '';
$myemail = 'mail#gmail.com';//
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']))
{
$errors .= "\n Будь ласка, заповніть усі поля";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['phone'];
$page = getRequestURI();
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "Некоректна адреса e-mail";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "Нове замовлення туру: $page".
"Деталі:\n Ім'я: $name \n Email: $email_address \n Телефон \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
I need to put such forms on different pages. And there should be information about the page on which form was submitted in the message sent by e-mail.
Is there a possibility to do that without creating separate php files for every page?
In other words how can I get the name (or url) of the page, on which form was submitted?
You can get the current request URI by using $_SERVER['REQUEST_URI'].
Assuming your script is located at http://example.com/some/page-here/more, $_SERVER['REQUEST_URI'] would be /some/page-here/more.
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
So have a single form which only gets the email of the person and sends it to the email address I assigned. But I guess I wrote the code in a wrong way since I am getting errors. I have seen other stackoverflow problems but I am not sure why this isnt working.
This is the form in html.
<form style="margin-bottom:50px;" name="contactform" action="contact-form-handler.php" class="news-letter "method="post">
<div class="subscribe-hide">
<input type="text" name="email" class="form-control" placeholder="Email Address" >
<button type="submit" class="btn"><i class="fa fa-envelope"></i></button>
</div><!-- /.subscribe-hide -->
</form><!-- /.news-letter -->
and here is the PHP code in a different file.
<?php
$errors = '';
$myemail = 'masnadhossain#live.com';
empty($_POST['email']))
{
$errors .= "\n Error: all fields are required";
}
$email_address = $_POST['email'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission";
$email_body = "You have received a new message. ".
" Here are the details:".
"Email: $email_address\n ";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
The error I get is server error 500
Your code have syntax error pleas check it.
Line no 3 should be:
if (empty($_POST['email']))
{
$errors .= "\n Error: all fields are required";
}
1.) The first problem you have is that you are sending the email address from a form input via post but you did not utilize it.
2.) To and From variables are having the same email address masnadhossain#live.com which is creating conflicts
3.) The Preg_Match for checking Email address validity is errorneous. I have re-written your code below.
If you are posting the users email(eg gmail,yahoomail etc) from a form input, this code will get you going.
In case you want to intialize the email within the code just change
$email_address = strip_tags($_POST['email']);
to may be
$email_address = 'user1#gmail.com';
Finally, the From variable must be the email address pointing to your website address. in this case I think it is masnadhossain#live.com
This code is working. please mark it as correct answer if it solve your problem....
<?php
//Users email address coming from form input eg. gmail,yahoomail etc.
$email_address = strip_tags($_POST['email']);
//validate the email address
$email_val= filter_var($email_address, FILTER_VALIDATE_EMAIL);
if (!$email_val){
echo "<font color=red><b>Invalid Email Address</b></font>";
exit();
}
$to=$email_val;
$subject = "Contact form submission";
$message = "Here is the message;
// set the from variable to any email pointing to your website
$from = "masnadhossain#live.com";
$headers = "From:" . $from;
$sent=mail($to,$subject,$message,$headers);
if($sent) {
print "<br><font color=green><b>Your mail was sent Successfully</b></font>";
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
} else {
print "<br><font color=orange><b>We encountered an error sending your mail.</b></font>";
}
?>
I am trying to create a hidden email field in my contact form that, when filled out, will not send me an email (meaning a spammer filled in the hidden email field), instead, just sending the spammer to a confirmation page saying that the email was sent.
I can't get it to work properly.
Test site - http://www.webexplosive.com/s1/contact.html
Here is my php script for the contact form:
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email1 = $_POST ['email1'];
$phone = $_POST ['phone'];
$comments = $_POST ['comments'];
$testBot = $_POST ['email2'];
$headers = "MIME-Version: 1.0\r\n";
$headers = "From: $email1";
$to = 'beefjelly69#yahoo.com';
$subject = 'Contact Form Submitted - Virginia Subsite';
$message = "
First name: $firstname \n
Last name: $lastname \n
Email: $email1 \n
Phone: $phone \n
Comments: $comments \n";
mail($to, $subject, $message, $headers);
header("Location: thankyou.html");
if(email2 == "") { //If email2 form section is blank then...
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email1 = $_POST ['email1'];
$phone = $_POST ['phone'];
$comments = $_POST ['comments'];
$testBot = $_POST ['email2'];
$headers = "MIME-Version: 1.0\r\n";
$headers = "From: $email1";
$to = 'beefjelly69#yahoo.com';
$subject = 'Contact Form Submitted - Virginia Subsite';
$message = "
First name: $firstname \n
Last name: $lastname \n
Email: $email1 \n
Phone: $phone \n
Comments: $comments \n";
mail($to, $subject, $message, $headers);
header("Location: thankyou.html");
}
else {
header("Location: thankyou.html");
}
?>
Code Technique
The best way, I've seen for weeding out bots and spammers in conmment and public forms, without captcha. Is to generate a random md5 hash (each refresh, should render the previous hash useless), store said hash in a cookie (for POST retrieval). Then append the hash string to each input[name=username_d109770c2788b022deb0fac1182c9e19] (I'd also POST the hash on the form, and validate the POST against the cookie).
The benefit to hashing input fields is.. it will increase the difficulty of bots being able to hard code to specific inputs (plus passive server validation).
Once you've done this simply add input validation such as email regular expressions and so fourth.
Security Technique
Install the honeypot project to your server, it has 101,130,389 spam servers identified as of 8:48 PM, 19/02/2014 (UTC+12:00).
Project Honey Pot is a web based honeypot network which uses software embedded in web sites to collect information about IP addresses used when harvesting e-mail addresses for spam
This is because you always call the mail form first. You need to validate it before you call it. Call the mail function after you have checked that the email2 field is empty.
As it is, it will always send the mail, before hitting the if statement.
Suggestion: Look into implementing a captcha or something similar than that.
Here's a revised version of your code with basic form validation (but it only checks for empty fields, it doesn't check if the e-mail is valid - you can easily add that though) and more importantly, email header injection protection.
Note : I didn't test this code and it may fail miserably - feel free to downvote if that's the case
// Form validation, display errors
// in case of empty fields
$fields = ["firstname", "lastname", "email1", "phone", "comments"]
foreach ($fields as $field) {
if (!isset($_POST[$field]) || empty($_POST[$field])) {
die("Error, ".$field." can't be empty, please retry."); // if validation fails we stop the script
}
}
if (isset($_POST["email2"]) && !empty($_POST["email2"])) {
die(); // hidden field isn't empty, so it's spam, so we stop there
}
// e-mail header injection protection
$email1 = filter_var($_POST["email1"], FILTER_SANITIZE_EMAIL);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$phone = $_POST ['phone'];
$comments = $_POST ['comments'];
$headers = "MIME-Version: 1.0\r\n";
$headers = "From: $email1";
$to = 'beefjelly69#yahoo.com';
$subject = 'Contact Form Submitted - Virginia Subsite';
$message = "
First name: $firstname \n
Last name: $lastname \n
Email: $email1 \n
Phone: $phone \n
Comments: $comments \n";
mail($to, $subject, $message, $headers);
header("Location: thankyou.html");
(A late answer, but could prove to be useful down the road).
Generally, SPAMBOTS will look for a form element called email or contact or any visible input they can put their little spammy hands on.
What you could do is to show/mark an input stating "If you're human, DO NOT fill this".
For example:
If you're human, DO NOT fill this: <input type="text" name="email">
then check if the field is not empty. If it is not empty and (most likely) filled in by the SPAMBOT, then make it die(); or redirect.
For example: and using an if(isset... from a named submit button:
<input type="submit" name="soobmeet" value="Send">
Sidenote: I chose "soobmeet" because it's generally not a good idea to name it "submit" etc.
(Something I learned recently from one the BIG GUNS here on SO)
PHP
<?php
if(isset($_POST['soobmeet'])){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email1 = $_POST ['email1'];
$phone = $_POST ['phone'];
$comments = $_POST ['comments'];
$email = $_POST ['email'];
if(!empty($_POST['email'])){
header("Location: get_lost.html");
// or make it die();
}
else{
$headers = "MIME-Version: 1.0\r\n";
$headers = "From: $email1";
$to = 'email#example.com';
$subject = 'Contact Form Submitted - Virginia Subsite';
$message = "
First name: $firstname \n
Last name: $lastname \n
Email: $email1 \n
Phone: $phone \n
Comments: $comments \n";
mail($to, $subject, $message, $headers);
header("Location: thankyou.html");
}
}
?>
First of all, I honestly don't recommend this as a spam/bot deterrent - there are many well tested third party libraries out there for you to use. Having said that, I've edited your code with some minor improvements. Hope this helps somewhat.
<?php
// Note: It is your own responsibility to validate user input!
if(isset($_POST['email2']) && $_POST['email2'] != "") {
$strFirstName = $_REQUEST['firstname'];
$strLastName = $_REQUEST['lastname'];
$strEmail = $_REQUEST['email1'];
$strPhone = $_REQUEST['phone'];
$strComments = $_REQUEST['comments'];
$strTestBot = $_REQUEST['email2'];
$strBody = "First name: ".$strFirstName." \nLast name: ".$strLastName." \nEmail: ".$strEmail." \nPhone: ".$strComments." \n";
mail('beefjelly69#yahoo.com', 'Contact Form Submitted - Virginia Subsite', $strBody, 'From: '.$strEmail);
header("Location: thankyou.html");
} else {
header("Location: thankyou.html");
}
?>
Is this what you're trying to achieve? Also, you should be validating each of the fields e.g. checking whether they're empty, of the right format and length etc. preg_match() is an awesome way of doing this, plus you can add some minor validation at the client side as well.
I have a single page portfolio website that I'm building and I have a contact form that I need to process using php send script. I'm a novice when it comes to PHP so I'm having trouble getting this to work. I've done some searching but I can't find what I'm looking for.
Here's what I have done, I copied this from a PHP contact page that I had built but the PHP and form are on the same page and I need an external send.php to process my form.
<?php
$error = ''; // error message
$name = ''; // sender's name
$email = ''; // sender's email address
$company = ''; // company name
$subject = ''; // subject
$comment = ''; // the message itself
if(isset($_POST['send']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$company = $_POST['company'];
$subject = $_POST['subject'];
$comment = $_POST['comment'];
if($error == '')
{
if(get_magic_quotes_gpc())
{
$message = stripslashes($message);
}
// the email will be sent here
// make sure to change this to be your e-mail
$to = "example#email.com";
// the email subject
// '[Contact Form] :' will appear automatically in the subject.
// You can change it as you want
$subject = '[Contact Form] : ' . $subject;
// the mail message ( add any additional information if you want )
$msg = "From : $name \r\ne-Mail : $email \r\nCompany : $company \r\nSubject : $subject \r\n\n" . "Message : \r\n$message";
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
}
}
if(!isset($_POST['send']) || $error != '')
{
header("location: http://www.#.com/#contact");
}
?>
So for my form I want to have:
<form method="post" action="send.php" class="form">
I plan on using HTML5 and jQuery to validate the form, so I really only need the script to capture the info and send the email to a single address. After it sends I want the script to redirect back to the Contact page.
Edit:
I found a solution after spending a while on google.
http://www.website.com/#contact");
?>
For one thing, you haven't initialized the value for $message
$message = stripslashes($message);
You probably meant to use $comment instead of $message
Not sure what problem you're facing. Simply copy the PHP you have into a file called send.php and my first glance says it'll work if you change $message back to $comment and add error checking. If you still have issues, post back with more details.
I'm using a PHP form to forward data to an email address. Everything seems to work fine except the the error message ["You have not entered an email"] appears when the page is loaded, before any input from the user is entered, rather than through validation when submitted.
The form is here http://www.soulwatt.com/contact.php
Note: I found this PHP code online after doing a search on how to forward data to email, so it is not mine. Please excuse the lack of proper code formatting.
<?php
$to = $_REQUEST['sendto'] ;
$from = $_REQUEST['Email'] ;
$name = $_REQUEST['Name'] ;
$headers = "From: $from";
$subject = "soulwatt.com Contact Data!!";
$fields = array();
$fields{"Name"} = "Name";
$fields{"Company"} = "Company";
$fields{"Email"} = "Email";
$fields{"Phone"} = "Phone";
$fields{"list"} = "Mailing List";
$fields{"Comments"} = "Comments";
$body = "Soul Watt has received the following information:\n\n";
foreach($fields as $a => $b) {
$body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]);
}
$headers2 = "From: noreply#soulwatt.com";
$subject2 = "Thank you for contacting Soul Watt!";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.soulwatt.com";
if($from == '') {
print "You have not entered an email. Please enter your email and try again.";
}
else {
if($name == '') {
print "You have not entered a name.<br />Please enter your name and try again.";
}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send) {
print "<p><span>THANK YOU FOR CONTACTING US!</span></p>";
print "<p><span>Someone will get back to you as soon as possible, usually within 48 hours. If you need immediate assistance regarding booking Soul Watt, please call Randy at (828) 729-3199.</span></p>";
}
else {
print "<p><span>We encountered an error sending your mail, please notify webmaster#soulwatt.com</span></p>";
}
}
}?>
Thanks for your help!
These 2 lines:
$from = $_REQUEST['Email'] ;
if($from == '') {
print "You have not entered an email. Please enter your email and try again.";
}
Mean that you check the email request (POST and GET) key. The first time you load this page this WILL be empty. You could add a check if there was a POST at all, for instance if there was submitted.
To be honest, there might a lot of problems with your code: a user can add all sorts of stuff in there, probably even add stuff in the headers to add 'to' fields and all.. You might be making a spam-machine here. This part: $headers = "From: $from"; just adds the request field FROM in your headers....
You'd want to wrap your validation section in
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do validation here ...
}
... print form here ...
That will only run the validation code AFTER you submit the form. As it stands now, it's running each time the page is loaded, so of course there's no form data to validate the first time around.
Does your form fields have the same name that you're checking?
I mean for
$from = $_REQUEST['Email'];
You should have
<input type='text' name='Email' /> <!-- Note the Capital E -->
I add my comments here:
Use $_POST or $_GET. Avoid $_REQUEST. That way you've more controll over your app.
Also, don't check emptiness with =="" try empty($from)
OK So if the form is on http://www.soulwatt.com/contact.php and you have
<form method="post" action="contact.php" name="contact_form" id="contact_form">
action="contact.php" : That means it is proccessing the form on the same address so you will see the results of the form processing on the same page, and since the form is empty, and you're checking it regardless of it having been posted or not, you get that error