How do I validate my email submission on php? - php

I'm just getting into coding and put together a webpage using dreamweaver. I created a php page with my email coding which is executed from a form and submit button on an html page. I continously recieve blank emails on a daily basis which apparently means I need to add validation coding. I tried adding the coding but the problem persists. The page still submits even if the form is blank.
Below is my current coding.
<?php
if(!filter_var($_POST['CustomerEmail'], FILTER_VALIDATE_EMAIL)) { $valerrors[] = "The email address you supplied is invalid." ;}
$customeremail=$_POST['CustomerEmail'];
$email='test#gmail.com';
$custfirst=$_POST['CustomerFirstName'];
$custlast=$_POST['CustomerLastName'];
$custphone=$_POST['CustomerNumber'];
$custaddress=$_POST['CustomerAddress'];
$custcity=$_POST['CustomerCity'];
$custstate=$_POST['CustomerState'];
$custrequest=$_POST['CustomerService'];
$subject='Service Request';
$body = <<<EOD
<br><hr><br>
Email: $customeremail <br>
First Name: $custfirst <br>
Last Name: $custlast <br>
Phone: $custphone <br>
Address: $custaddress <br>
City: $custcity <br>
State: $custstate <br>
Request: $custrequest <br>
EOD;
$headers = "From: $customeremail\r\n";
$headers .= "Content-type: text/html\r\n";
$Send = mail($email, $subject, $body, $headers);
$confirmation = <<<EOD
<html>"Thanks for Submitting."</html>
EOD;
echo"$confirmation";
?>
It's possible that I'm placing the if statement in the wrong place. Can someone correct my coding so the confirmation page will not load and the email will not be sent if the customer email is left blank?

You need to check like this
if (filter_var('abc#gmail.com', FILTER_VALIDATE_EMAIL)) {
echo 'VALID';
} else {
echo 'NOT VALID';
}
see here : http://php.net/manual/en/function.filter-var.php

You could initialize $valerrors = []; at the beginning and use a condition such as:
if (empty($valerrors)) {
$headers = "From: $customeremail\r\n";
$headers .= "Content-type: text/html\r\n";
$Send = mail($email, $subject, $body, $headers);
$confirmation = <<<EOD
<html>"Thanks for Submitting."</html>
EOD;
}
Note that you should apply similar validation to all user inputs.

I think u can add "required" attribute to your email input in your form Html
<input type="email" name="CustomerEmail" required>
So Html wont allow you to submit until you provide a value

Related

html contact form doesn't recognise php file

------THE CODE HAS BEEN MODIFIED SINCE FIRST POST------
For the life of me, I cannot get this to work. The page mentioned below will not recognise the email.php file in the root theme folder. I've tried everything!
Purpose: HTML contact form for a user to submit their details, PHP Script collects the users first name, last name and email address and in turn, redirects them to a thank you page.
Problem: HTML contact form displays fine, but when I click on "Okay, send me a voucher code!" it comes up with URL: http://charliesonlinestore.com/free-delivery-coupon-page/email.php with 'Nothing found', when it should be re-directing to a thank you page.
Here is the form code from HTML:
<div class="form">
<form method="post" name="landing-page" action="<?php echo get_template_directory_uri(); ?>/email.php">
First Name<br>
<input type="text" name="first_name"><br><br>
Last Name<br>
<input type="text" name="last_name"><br><br>
Email Address<br>
<input type="text" name="email"><br><br>
<input type="submit" name="submit" value="Okay, send me a voucher code!">
</form>
</div>
Here is my PHP Script code:
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_from = $_POST['email'];
$to = 'charlie#charliesonlinestore.com';
$body = 'Here your email body text';
$subject = 'NEW Subscriber';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: Lead Generator <Charlie#charliesonlinestore.com>' .
"\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
if($_POST['submit']){
if(mail($to, $subject, $headers)){
echo "mail send"; // change this later to your header location
}
else{
echo 'error sending mail';
}
}
else{
echo 'no post data';
}
?>
Confirmed points:
The email.php is in the root of the theme folder, storefront.
All items in the example are provided in the root folder, storefront.
When I tested this on local host (separate server), it worked fine and redirects without issues.
If you have any ideas on why this is happening then I would greatly appreciate it. I've almost completed my very own custom built contact form, lead generation and thank you page!
Just to note, I have checked previous posts and tried things such as putting a '/' infront of the PHP file name and also tried putting the file server address infront of the file name but to no avail.
Please help!
It tooks a little time before i saw it. The problem is your mail function. The php mail function needs a message before headers. And you replace your $header variable instead of extending it.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$to = 'charlie#charliesonlinestore.com';
$body = 'Here your email body text';
$subject = 'NEW Subscriber';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: Your name <Charlie#charliesonlinestore.com>' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
if($_POST['submit']){
if(mail($to, $subject, $body, $headers)){
echo "mail send"; // change this later to your header location
}
else{
echo 'error sending mail';
}
}
else{
echo 'no post data';
}
?>

Issues developing companion php for natural language form

Forgive me, I am new at this and the different php I have tried hasn't really worked at all. I've found examples for Natural Language forms, but none with working PHP and I'm familiar with PHP when used with traditional forms, but I'm having problems putting the two together.
The general form layout goes like this:
My name is [your name].
Today, I am [whatchya gonna do?].
I'm doing this because [c'mon,why?].
It's important that I [what you said you'd do] because [the big picture].
Shoot me an email with my awesome new declaration at [your email]
Button 1 (sends email)
Button 2 (copies all text and input fields to clipboard -- not as important right now)
Button 1, I want to send a copy to myself with a hard coded email address and also send a copy to the user with the email address they've entered.
This is a little messy right now, as I am simply trying to get it to work... again, I have no included PHP because at this point -- I've confused myself so much that I don't know what to include.
<form method="post" action="todayiam.php">
<div class="naturallanguageform">
<div class="nlfinner">
<p class="line">
<span class="copy">My name is </span>
<span class="inputcontainer"><input class="textinput" name="name" value="" placeholder="[your name]">.</span>
<span class="copy">Today, I am </span>
<span class="inputcontainer"><input class="textinput" name="todayiam" value="" placeholder="[whatchya gonna do?]">.</span>
<span class="copy">I'm doing this because </span>
<span class="inputcontainer"><input class="textinput" name="why" value="" placeholder="[c'mon, why?]">.</span>
<span class="copy"> It's important that I </span>
<span class="inputcontainer"><input class="textinput" name="whatusaid" value="" placeholder="[what you said you'd do]"></span>
<span class="copy"> because </span>
<span class="inputcontainer"><input class="textinput" name="because" value="" placeholder="[the big picture]">.</span>
</p>
<span class="copy">Shoot me an email with my awesome new declaration at</span>
<span class="inputcontainer"><input class="textinput" name="email" value="" placeholder="[your email]"></span>
<p class="line">
<button class="button">Send to E-mail</button>
</p>
<p class="line">
<button class="button">Copy to post in comments</button>
</p>
</div>
</div>
</form>
Any assistance will be greatly appreciated.
Update:
<?php
// from the form
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['todayiam']);
// set here
$subject = "Contact form submitted!";
$to = 'email#gmail.com';
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
// redirect afterwords, if needed
header('Location: index.html');
?>
Another update
I have changed $headers = "From: $email\r\n"; to $headers = "From: email#gmail.com" . "\r\n" ; to set a static from address (my support email) and the email is still identifying as from CGI Mailer. I have verified that it's not a caching issue and the correct files are being used.
<?php
if (isset($_POST['name'], $_POST['todayiam'], $_POST['why'], $_POST['whatusaid'], $_POST['because'], $_POST['email']) {
// We enter this statement only if all the fields has been properly defined, this to avoid getting undefined index
$name = $_POST['name'];
$todayIam = $_POST['todayiam'];
$why = $_POST['why'];
$whatYouSaid = $_POST['whatusaid'];
$because = $_POST['because'];
$email = $_POST['email'];
// We define the variables for using in mail()
$to = 'email#gmail.com';
$to .= ', '.$email; // You wanted them to recieve a copy
$subject = "Contact form submitted!";
// You can put a lot more headers, check out the mail() documentation
$headers = "From: email#gmail.com" . "\r\n" ;
$headers .= "Content-type: text/html\r\n";
// Compose a $message from all the variables
$message = "My name is $name. ";
$message .= "Today, I am $todayIam.";
$message .= "I'm doing this because $why.";
$message .= "It's important that I $whatYouSaid";
$message .= "because $because.";
if (mail($to, $subject, $message, $header)) {
// Mail was successfully sent! Do something here
}
}
?>
Before you posted your answer, I was working on this script:
<?php
// from the form
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['todayiam']);
// set here
$subject = "Contact form submitted!";
$to = 'email#gmail.com';
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
// redirect afterwords, if needed
header('Location: index.html');
?>
The $email = trim(strip_tags($_POST['email'])); field was pulling the user's email and using it for the sent from as noted in the $header... so it was working fine. With the new script, that you posted, I can't get it to work with my hard coded email OR the user's email as the FROM. Initially, I really wanted to understand what the differences were between the script, why one worked and the other didn't, but now... I'd really just like my email to be hard coded as the FROM. I'll worry about the differences later. As I said before, I really have tried to get this to work in many different forms... I am sure it's something simple that I am over looking as a novice to PHP. Thanks.
Right, so after a bit of discussion from comments, I decided to post an answer instead, giving a bit more detail where it's more readable.
Your PHP code is missing the combination of all fields into $message. This can easily be done, as you can put a variable inside a string in PHP. I'll show you how. I'm also going to show you how you can avoid undefined indexes.
<?php
if (isset($_POST['name'], $_POST['todayiam'], $_POST['why'], $_POST['whatusaid'], $_POST['because'], $_POST['email']) {
// We enter this statement only if all the fields has been properly defined, this to avoid getting undefined index
$name = $_POST['name'];
$todayIam = $_POST['todayiam'];
$why = $_POST['why'];
$whatYouSaid = $_POST['whatusaid'];
$because = $_POST['because'];
$email = $_POST['email'];
// We define the variables for using in mail()
$to = 'email#gmail.com';
$to .= ', '.$email; // You wanted them to recieve a copy
$subject = "Contact form submitted!";
// You can put a lot more headers, check out the mail() documentation
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Compose a $message from all the variables
$message = "My name is $name. ";
$message .= "Today, I am $todayIam.";
$message .= "I'm doing this because $why.";
$message .= "It's important that I $whatYouSaid";
$message .= "because $because.";
if (mail($to, $subject, $message, $header)) {
// Mail was sucsessfullly sent! Do something here
}
}
?>

PHP mailer change variable based on variable from dropdown menu

I am working on a mailer and form. In my form I have a dropdown menu that is populated from a database. The table in the database has 3 columns: id, facility, and email. I need the mailer side to look at the facility and change $mailto to the corresponding email address from the database. I am really new and this has had me stumped for two days.
Dropdown from form.php:
$queryData = "SELECT * FROM facilities";
$result = mysql_query($queryData);
?>
<select id="cust_Facility" name="cust_Facility">
<?php
while($row = mysql_fetch_array($result))
{
?>
<option value=<?php echo($row['id']); ?>><?php echo($row['facility']); ?></option>
<?php
}
?>
</select>
<?php
?>
Form:
$emailSubject = 'Toner Request';
$mailto = '';
$email = 'Toner Sending Service';
$facilityField = mysql_real_escape_string($_POST['cust_Facility']);
$queryEmail = "SELECT * FROM facilities WHERE ";
$result = mysql_query($queryEmail);
if (isset($facilityField)) {
echo "Facility is set";
}
$body = <<<EOD
<br><hr><br>
Customer Information<br>
<br>
Facility: $facilityField <br>
EOD;
$headers = "From: $email\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Success!</h2>
</body>
</html>
When I hit submit on my form it echoes $facilityField as expected. I don't know what to add after that to make it change $mailto based on what value is in $facilityField. When I set $mailto manually I receive the email as expected.
New mail:
<?php
include('db.inc');
$emailSubject = 'Toner Request';
$mailto = '';
$email = 'Toner Sending Service';
$facilityField = mysql_real_escape_string($_POST['cust_Facility']);
$queryEmail = "SELECT email FROM facilities WHERE facility = '".$facilityField."'";
$result = mysql_fetch_assoc($queryEmail);
echo "$result\n";
if (isset($facilityField)) {
echo "Facility is set";
}
$body = <<<EOD
<br><hr><br>
Facility: $facilityField <br>
EOD;
$headers = "From: $email\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
//$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Success!</h2>
</body>
</html>
I made the changes above according to my understand of Pogrindis' comment. It doesn't echo $result. It just gives me the echo "Facility is set" and "Success!". What am I still missing?
The final working code:
$queryEmail = "SELECT email FROM facilities WHERE facility = '$facilityField'";
$result = mysql_query($queryEmail);
$result = mysql_fetch_assoc($result);
$mailto = $result['email'];
Your body is not in a a string. You should be getting an error.
Your $body var should be something llike :
$body = "<<<EOD
<br><hr><br>
Customer Information<br>
<br>
Facility:". $facilityField ."<br>
EOD";
Then you will be able to use it in your mail function.
At the moment however if the facilty is not set it is still trying to send the email. So an undefined error will occur.
Cleaning if your If statement should help with this.
if (isset($facilityField)) {
echo "Facility is set";
$body = "<<<EOD
<br><hr><br>
Customer Information<br>
<br>
Facility:". $facilityField ."<br>
EOD";
$headers = "From: $email\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
}
else
echo "Please set facility. "
?>
Something a bit more verbose as to what is going on would be helpful also.
Also your $mailto; at the top of the page is not defined.
If you have it on the form you should have an email input (to send to this email.) Or if it to you like a contact page it should be set.
if(isset($_POST['emailFormName']))
$mailto = $_POST['emailFormName'];
The mailto is now set from the form input called emailFormName.
As your update asked how to populate the mailto based on the facility.
You should be using
$mailto = $_POST['cust_Facility'];

PHP get form not receiving email

I'm using a simple web form and some PHP script to send the completed form to my email. When I hit "Submit" I get the PHP text "Thanks, we'll be in touch shortly" but I'm not getting the email with submitted form info. Not sure what's the problem.
from the HTML doc:
<div class='' "letstalk_form">
<form method="get" action="contact.php" name="contact" id="contact">
<p>
<label for="txtfname">Name:</label><input type="text" tabindex="1" name="txtfname" id="txtfname" class="clsTextBox">
</p>
<p>
<label for="txtcompany">Company:</label><input type="text" tabindex="2" name="txtcompany" id="txtcompany" class="clsTextBox">
</p>
<p>
<label for="txtemail">E-mail:</label><input type="text" tabindex="3" name="txtemail" id="txtemail" class="clsTextBox">
</p>
<p>
Message:<textarea name="comments" id="comments" rows="2" cols="20"></textarea>
</p>
<p class="submit">
<input type="submit" value="Submit">
</p>
</form>
</div>
and the PHP
$msg = "Sender Name:\t$txtfname\n";
$msg .= "Sender Company:\t$txtcompany\n";
$msg .= "Sender E-mail:\t$txtemail\n";
$msg .= "Comments:\t$comments\n\n";
$recipient = "receiversemail#somewhere.com";
$subject = "from PI Website";
$mailheaders = "From: Lets Do Business <> \n";
$mailheaders .= "Reply-To: $txtemail\n\n";
mail($recipient, $subject, $msg, $mailheaders);
echo "<HTML><HEAD><TITLE>Form Sent!</TITLE></HEAD><BODY>";
echo "<H3 align=center>Thank You, $txtfname</H3>";
echo "<P align=center>Your submission was sent successfully.<br />
I will be contacting you soon.</P>";
echo "</BODY></HTML>";
?>
</div>
I've used this is the past and worked great. Is there something I overlooked? Thanks for you help!
EDIT: I ended up using the link Turgut Dursun provided (html-form-guide.com/contact-form/php-email-contact-form.html ) to set up the form. Works great. Thanks.
Are you assigning the $_GET[] values from the form to variables prior to this portion of your code?
$msg = "Sender Name:\t$txtfname\n";
$msg .= "Sender Company:\t$txtcompany\n";
$msg .= "Sender E-mail:\t$txtemail\n";
$msg .= "Comments:\t$comments\n\n";
$recipient = "abosiger#embarqmail.com";
$subject = "from PI Website";
$mailheaders = "From: Lets Do Business <> \n";
$mailheaders .= "Reply-To: $txtemail\n\n";
mail($recipient, $subject, $msg, $mailheaders);
If not, you need to either initialize your $_GET[] values to individual variables:
$txtfname = $_GET['textfname'];
for each variable sent through get. Or you can access them directly from the $_GET array through the following syntax:
$msg = "Sender Name:\t" . $_GET['txtfname'] . "\n";
Let me know if this helps.
<?php
$to = "someone#example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse#example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
change it like this.
The problem probably comes from a bad configuration of the mail function. You have to configure it properly.
Also, you should provide an email in the "From" header.
if message sent and no mails is receieved, this authenticating issues from your domain
... your script might works fine
The two main ways to do this is either using PHPMail() or SMTP. PHPMail() is open and used by trojans and viruses. Most clients have infected files which just send mails using PHPMail(), because it doesn't authenticate. It doesn't check if the email being sent is actually coming from the domain and this puts a lot of strain on the mail server, making legitimate mails wait in queue for a long time.
If you already have a script using PHPMail() function it is very simple to change it to SMTP, you just need to change like 5 lines of your code and add an email address and password (already created in cpanel) into the code, and it will send emails just fine.
if ($_POST['submit']){
$from = "slick#meetslick.com"; //enter your email address
$to = "slickbozz#gmail.com"; //enter the email address of the contact your sending to
$subject = "Contact Form"; // subject of your email
$headers = array ('From' => $from,'To' => $to, 'Subject' => $subject);
$text = ''; // text versions of email.
$html = "<html><body>Name: $name <br> Email: $email <br>Message: $message <br></body></html>"; // html versions of email.
$crlf = "\n";
$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
//do not ever try to call these lines in reverse order
$body = $mime->get();
$headers = $mime->headers($headers);
$host = "localhost"; // all scripts must use localhost
$username = "support#meetslick.com"; // your email address (same as webmail username)
$password = " here "; // your password (same as webmail password)
$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true,
'username' => $username,'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
}
else {
echo("<p>Message successfully sent!</p>");
// header("Location: http://www.meetslick.com/");
}
}
I hope this will be helpful to someone one day.

PHP tweaking on a mail form

I got some help with an email form, and I feel that I am almost there as the script sends an email but need a few tweaks before I put the form up. Here is my code right now:
index.html:
<div id="main">
<form method="post" action="mailer.php">
<div id="text">
Please enter your email address.
</div>
<input type="text" name="q" id="search" />
<input type="submit" name="submit" id="submit" value="Go!" />
</form>
</div>
mailer.php:
<?php
$email = addcslashes($_REQUEST['q']) ;
if ($email==FALSE){
echo "You forgot to enter your email";
}
else
mail( "example#gmail.com", "E-Mail entered",
"E-Mail entered: $email");
header( "Location: http://www.example.com/thankyou.html" );
?>
A few issues I am running into:
The email being sent does not actually include the email entered, the email comes from Apache#ipaddress.ec2.internal and the Body is Email Entered:
which does not include the email string - is there something buggy with the code?
Also, my if statement doesn't seem to work. Even if I leave the box black, it still assumes a valid email address was sent.
Finally, is there a parameter that sees if the address is in the correct format? ie: includes the # the . and the domain?
Many thanks for any help!
First off, you can use filter_var($email, FILTER_VALIDATE_EMAIL) to test the submitted address. This function returns false if it's not valid. Second, mail() requires a 4th parameter to assign a return address in your message header. Here's an example:
mail(
'to#address.com',
'Subject',
'Message Body',
'From: from#address.com'
)
Regarding your if/else statement, test $_POST['q'] == NULL first, then change $email = addcslashes($_REQUEST['q']); to $email = str_replace(array('\'', '"'), '', $_POST['q']); - no real reason to escape characters in this case. Just take em' out.
Edit: This is what your code should look like:
$email = str_replace(array('\'', '"'), '', $_POST['q']);
$isValid = filter_var($email, FILTER_VALIDATE_EMAIL);
if ( $_POST['q'] == NULL ) {
echo "You forgot to enter your email";
} elseif ( $isValid == FALSE ) {
echo "Please enter a valid email address";
} else {
mail(
'example#gmail.com', // Your address that you want the message sent to
'Subject',
'Message Body',
'From: ' . $email // The address collected
);
header( "Location: http://www.example.com/thankyou.html" );
}
Does that make a little more sense?
Do note that because of modern spam filters, this method may not make it to every recipient. Creating useful email headers can be a bit of an art-form that takes some practice.
To change the "from field", try something like this:
// Additional headers
$headers .= 'To: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
As far as your if statement, check the $_REQUEST variable first:
if (isempty($_REQUEST['q']) { echo "forgot to enter email"; }
Finally, here's a link to a method to validate email addresses: http://www.linuxjournal.com/article/9585
Try this for checking if the email is set.
if(isset($_REQUEST['q'])) ..
As far as the "Email Sender". I believe you are looking for the "From" header.. that can be done like this..
$header = "From: Your Name <example#gmail.com>";
mail($to, $subject, $message, $header);
More details are available at http://us3.php.net/manual/en/function.mail.php

Categories