Hey guys,
I know there are a lot better ways to send email with PHP. However, for this purpose the easiest solution is perfect. Only thing: I can't find out why, my validation is not working!
I get the email address, however the validation is not working, I'm able to send a completely empty form. Any ideas?
<?php
//Email
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Comment = Trim(stripslashes($_POST['comment']));
$EmailTo = "myemail#address.com";
/*$Name = "Some Name";
$EmailFrom = "test#test.com";
$Subject = "Test";
$Comment = "Why is the validation not working, don't get it?";
$EmailTo = "myemail#address.com";*/
/*echo $Name . " length: " . strlen($Name) . "<br/>";
echo $EmailFrom . " length: " . strlen($EmailFrom) . "<br/>";
echo $Subject . " length: " . strlen($Subject) . "<br/>";
echo $Comment . " length: " . strlen($Comment) . "<br/>";
echo $EmailTo . " length: " . strlen($EmailTo) . "<br/>";*/
//***************************
//Validation
//***************************
$validationOK=true;
if ($Name == "") $validationOK=false;
if (isValidEmail($EmailFrom) == 0) $validationOK=false;
if ($Subject == "") $validationOK=false;
if ($Comment == "") $validationOK=false;
function isValidEmail( $email = null ) {
return preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix", $email );
}
if (!$validationOK) {
print "error";
}
//***************************
//Order
//***************************
$Body = "Contactform";
$Body .= "\n\n";
$Body .= $Comment;
// Email Headers with UTF-8 encoding
$email_header = "From: " . $EmailFrom . "\r\n";
$email_header .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_header .= "Reply-To: " . $EmailFrom . " \r\n";
// send email
$success = mail($EmailTo, $Subject, $Body, $email_header);
//***************************
//Success or Error
//***************************
if ($success){
print "success";
}
else{
print "error";
}
?>
you need to return after the condition
if (!$validationOK) {
print "error";
// return or exit
}
dont continue to send mail
You don't end your script after printing "error". You should end the script or make some other change so it won't be sent on error. For example:
if (!$validationOK) {
print "error";
exit;
}
You're printing the word error if $validationOK is false but you're not halting the script at that point so php continues to process the commands after it.
Try the following
if (!$validationOK) {
print "error";
exit();
}
This code:
if (!$validationOK) {
print "error";
}
does not keep your program from sending a mail, it just prints error message.
Don't write your own email validation function when there's tried and tested free software to do it for you.
You are welcome to use my free PHP function is_email() to validate addresses. It's available to download [here][1].
It will ensure that an address is fully RFC 5321 compliant. It can optionally also check whether the domain actually exists and has an MX record.
You shouldn't rely on a validator to tell you whether a user's email address actually exists: some ISPs give out non-compliant addresses to their users, particularly in countries which don't use the Latin alphabet. More in my essay about email validation here: [http://isemail.info/about][2].
Related
I have a form that sends data to the script below. It's supposed to send a message from the person specified in the form's emailaddress. Instead, I get it coming from a strange email address from my hosting company. I've checked the php over and over again and can not find out where the issue is. The email does send... just from the wrong address...
<?
// set recipient email
$mymail = "thelamp.website#yahoo.com";
// get information from form
$name = $_POST['firstname'] . " - " . $_POST['lastinitial'];
$email = $_POST['emailaddress'];
$multiplemail = $mymail . ", " . $email;
$message = $_POST['testimonial'];
$message = wordwrap($message, 200, "\r\n");
$subject = "Testimonial Submission: ";
date_default_timezone_set('US/Eastern');
$body = "Date: " . date('m-d-Y') . " - Time: " . date('h:i:s A e') . "\n Name: " . $name . "\n eMail: <" . $email . "> \n wrote: \n" . $message;
$headers = "To:" . $email . ", " . $mymail . ", From:" . $email;
// check the eMail!
$emailB = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($emailB, FILTER_VALIDATE_EMAIL) === false || $emailB != $email)
{
// Display error message!
echo "This eMail adress that you entered in the form is invalid! Please go back and enter a correct eMail address!";
// Exit the checking scriptlet!
exit(0);
}
else
{
if(!mail($multiplemail, $subject, $body, $headers))
{
// Testimonial was NOT sent
die ("Testimonial could not be sent! Please try again later!");
}
else
{
// Testimonial was successfully sent
?><meta http-equiv="refresh" content="0; URL=thankyou.html"><?
}
}
?>
Any help you can give me would be greatly appreciated. Thanks in advance.
Notice: Undefined variable: error in
/storage/ssd5/047/2981047/public_html/inc/sendEmail.php on line 47
OK
this error is being shown when I send an email from my own site...
I want to find a solution to this since the error is being shown on the site itself, not in the console, etc...
The message up is what is being shown on my site when the form is filled correctly...
Please, not I have no experience in PHP.
<?php
$siteOwnersEmail = '*********************';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message = "";
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//Error Starts is her if im not mistaken....
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
When you call if (!$error) { the variable $error might not have been created - it only comes into existence when either the length test or regex test fail.
As the $error variable seems to be an array when it is created you ought to create a default empty variable. You ought to also check for the other POST variables being available before trying to use them or similar errors will occur potentially.
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['contactName'],$_POST['contactEmail'],$_POST['contactSubject'],$_POST['contactMessage'] ) ){
$error=[]; # default, empty error variable
if (strlen($name) < 2) $error['name'] = "Please enter your name.";
/* etc */
if ( empty( $error ) ) {
/* try to send email */
} else {
/* errors happened - let user know or perform other tasks */
}
}
You have to assign default values to variable $error, for example
$error = '';
I am new to PHP, but know my way around HTML. I have been asked to implement a reCaptcha form into our site's PHP contact email form. I'm coming up empty. I have signed up and have my site key and secret key, just no idea how to integrate it into our form.
Here is our sites PHP form:
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "contact#########.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
Any help is appreciated. Thanks!
First, as a part of your form elements, include reCaptcha:
<?php
require_once("location/of/recaptchalib.php");
$publickey = "yourPublicKeyGoesHere";
echo recaptcha_get_html($publickey);
?>
in your send_email.php file you can do this:
<?php
session_start();
require_once("location/of/recaptchalib.php");
$timezone = "Asia/Kuwait";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
$privatekey = "YourPrivateKey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
else {
$sender_name = $_POST['sender_name'];
$sender_email = $_POST['sender_email'];
$query_type = $_POST['query_type'];
$ip = $_SERVER["REMOTE_ADDR"];
$date = date("d M Y H:i:s");
$sender_message = "Thank You for your message, ".$sender_name."\r\n"."Message was sent from ".$ip."on ".$date."\r\n".$_POST['sender_message'];
$headers = "From: Your Website" . "\r\n" .
"BCC: you#yourwebsite.com";
mail($sender_email,'Email from yourwebsite guest',$sender_message,$headers);
echo "Message Sent!";
}
?>
This worked for me, and the form looks like this:
I hope this helps.
I have VERY little experience with PHP.
I am testing out a contact form for this website. I am only getting the "subject, message, and header" fields in the email.
I need the telephone and name fields to show in my email message as well.
What am I doing wrong?
Any help is appreciated -- thanks!
<?php
$name;$email;$message;$captcha;$telephone;
if(isset($_POST['name'])){
$name=$_POST['name'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['telephone'])){
$telephone=$_POST['telephone'];
}if(isset($_POST['message'])){
$message=$_POST['message'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form. <a href=http://www.website.com#contact/>Back to Form</a></h2>';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcYjgcT****q9vhur7iH_O4dZPl4xUAVwW8=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}else
{
// Checking For Blank Fields..
if ($_POST["name"] == "" || $_POST["email"] == "" || $_POST["telephone"] == "" || $_POST["message"] == "") {
echo "Fill All Fields..";
} else {
// Check if the "Sender's Email" input field is filled out
$email = $_POST['email'];
// Sanitize E-mail Address
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email) {
echo "Invalid Sender's Email";
} else {
$to = 'email#gmail.com';
$subject = 'Contact Form';
$message = $_POST['message'];
$name = $_POST['name'];
$headers = 'From:' . $email . "\r\n";
// Sender's Email
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message .= "\r\n Name: " . $name;
$message .= "\r\n Email: " . $email;
$message .= "\r\n Telephone: " . $telephone;
$message .= "\r\n Message: " . $message;
// Send Mail By PHP Mail Function
if (mail($to, $subject, $message, $headers)) {
echo "Your mail has been sent successfully!<a href=http://wwwwebsite.com>Back</a>";
} else {
echo "Failed to send email, try again.";
exit ;
}
}
}
}
?>
The $message variable is the content of the mail that will be sent to your adress, add the values you want to get in your mail to that variable.
like so : (since you're not using HTML mail I think)
$message .= "\r\n Name : " . $name;
$message .= "\r\n Email : " . $email;
etc..
Before you call the mail function.
ALSO :
You're adding Phone number, Email, and message in your $email variable. you should give these their own variable.
The problem I'm having is that I want to pass through data from a number of fields in a form into one email send via PHP, the concerned code is as follows:
$mailcheck = spamcheck($_POST['inputemail']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{
// This still needs to be debugged online as soon as possible
$from = $_POST['inputemail'];
$name = $_POST['inputname'];
$phone = $_POST['inputphone'];
$date = $_POST['inputdate'];
$time = $_POST['inputtime'];
$data = $_POST['inputprotection'];
$subject = $_POST['inputdropdown'];
$message = $_POST['inputmessage'];
$message = wordwrap($message, 70);
mail("UP498701#myport.ac.uk",$subject,$message,"From: $from\n" . "Name: $name\n" . "Phone: $phone\n" . "Date: $date\n" . "Time: $time\n" . "Keep Data? $data\n");
echo "Thank you for sending us feedback, you'll be redirected in 5 seconds";
}
}
This is where I'm declaring all the information to be passed as a header for the email. The current PHP passes syntax check as works to the extent that an email is sent containing the $to, $subject, $message all fine, but the $header only passes through the final part (Keep Data? $data\n). When I remove all the other fields and simply keep the $data part, the email stops sending any $header. I also have an issue with the redirect, which has been removed from the below code and will be inserted as soon the current issue is resolved. The current full PHP is:
<html>
<body>
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
if (isset($_POST['inputemail']))
{
$mailcheck = spamcheck($_POST['inputemail']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{
// This still needs to be debugged online as soon as possible
$from = $_POST['inputemail'];
$name = $_POST['inputname'];
$phone = $_POST['inputphone'];
$date = $_POST['inputdate'];
$time = $_POST['inputtime'];
$data = $_POST['inputprotection'];
$subject = $_POST['inputdropdown'];
$message = $_POST['inputmessage'];
$message = wordwrap($message, 70);
mail("UP498701#myport.ac.uk",$subject,$message,"From: $from\n" . "Name: $name\n" . "Phone: $phone\n" . "Date: $date\n" . "Time: $time\n" . "Keep Data? $data\n");
echo "Thank you for sending us feedback, you'll be redirected in 5 seconds";
}
}
?>
</body>
and is temporarily hosted at http://luke-hale.com/temp/contact.html. I'm sure this is just a case of being misinformed on my part, but any help would be great, cheers!
EDIT:
okay so that issue is sorted with:
$subject = $_POST['inputdropdown'];
$message = $_POST['inputmessage'] . "\r\n\r\n" . $_POST['inputname'];
$message = wordwrap($message, 70);
$headers = "From: " . $_POST['inputemail'];
mail("UP498701#myport.ac.uk",$subject,$message,$headers);
echo "Thank you for sending us feedback, you'll be redirected in 5 seconds";
Which works though doesn't display the $headers anywhere, but I'm not too fussed about this, the next thing is the redirect, which I would usually run through via:
header("refresh:5;url=http://www.domain.com")
Though this was not working correctly earlier, I will apply an edit when tested for anyones future reference.
EDIT
So the form works but the re-direct does not. The site is still hosted on the same domain, but now the full PHP looks like this:
<html>
<body>
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
if (isset($_POST['inputemail']))
{
$mailcheck = spamcheck($_POST['inputemail']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{
$subject = $_POST['inputdropdown'];
$message = "Name: " . $_POST['inputname'] . "\r\n\r\n" . "Email: " . $_POST['inputemail'] . "\r\n\r\n" . "Phone: " . $_POST['inputphone'] . "\r\n\r\n" . "Date: " . $_POST['inputdate'] . "\r\n\r\n" . "Time: " . $_POST['inputtime'] . "\r\n\r\n" . "Retain Data? " . $_POST['inputprotection'] . "\r\n\r\n" . "Message: " . $_POST['inputmessage'];
$message = wordwrap($message, 70);
$headers = "From: " . $_POST['inputemail'];
mail("UP498701#myport.ac.uk",$subject,$message,$headers);
echo "Thank you for sending us feedback, you'll be redirected in 5 seconds";
}
}
header("refresh:5;url=http://www.domain.com")
?>
</body>
The form still sends fine but the return states that the line beginning "header" cannot be passed because the browser data has already been modified. I'm not sure sure what I've done or where so if anyone could lend a hand, that'd be great!
FINAL EDIT
My final, fully working, code:
<?php
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
ob_start();
if (isset($_REQUEST['inputemail'])&&($_REQUEST['inputname'])&&($_REQUEST['inputmessage']))
{
$mailcheck = spamcheck($_POST['inputemail']);
if ($mailcheck==FALSE)
{
echo "Invalid email, you'll be redirected ";
header("refresh:5;url=http://www.luke-hale.com/");
}
else
{
$subject = $_POST['inputdropdown'];
$message = "Name: " . $_POST['inputname'] . "\r\n\r\n" . "Email: " . $_POST['inputemail'] . "\r\n\r\n" . "Phone: " . $_POST['inputphone'] . "\r\n\r\n" . "Date: " . $_POST['inputdate'] . "\r\n\r\n" . "Time: " . $_POST['inputtime'] . "\r\n\r\n" . "Retain Data? " . $_POST['inputprotection'] . "\r\n\r\n" . "Message: " . $_POST['inputmessage'];
$message = wordwrap($message, 70);
$headers = "From: " . $_POST['inputemail'];
mail("UP498701#myport.ac.uk",$subject,$message,$headers);
echo "Thank you for your messgae, I'll get back to you as soon as possible! You'll be redirected in 5 seconds.";
}
header("refresh:5;url=http://www.luke-hale.com/");
}
else
{
echo "You did not fill all the required fields, please try again.";
header("refresh:5;url=http://www.luke-hale.com/");
}
?>
Try putting your form data into the $message variable, insert \n after each attribute to give a new line. Do not use the header.
Location and Refresh both require an absolute URI
header('Location: http://www.domain.com');
Examples for mail:
https://stackoverflow.com/a/22833890/3489793
https://stackoverflow.com/a/22831825/3489793
mail("Your Email Address Here",$subject,$therest,"subject: $subject\n");
U said this:
"The mail function is also not the issue, and correct syntax is" mail($to,$subject,$message,$headers,$parameters)
Explanation:
your email adress = $to
$subject = $subject
$therest = $message (rename it if you want)
"subject: $subject\n" = the header (change it to $headers if you want that)
Header example (as in the documentation)
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
You could echo a Javascript at the bottom of your PHP script which redirects instead, like this:
$url = "url";
$time = 5000 // time in milliseconds
print "<script>window.setTimeout(function(){window.location='".$url."'},".$time.") </script>"