I have the following code on one of my signup pages. I'm trying to figure out how to only generate the email if there are no errors...right now, it sends the email no matter what so I'm getting conflicting emails.
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
//Forms posted
if(!empty($_POST))
{
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$displayname = trim($_POST["displayname"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
$captcha = md5($_POST["captcha"]);
if ($captcha != $_SESSION['captcha'])
{
$errors[] = lang("CAPTCHA_FAIL");
}
if(minMaxRange(4,25,$username))
{
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT",array(4,25));
}
if(!ctype_alnum($username)){
$errors[] = lang("ACCOUNT_USER_INVALID_CHARACTERS");
}
if(minMaxRange(4,60,$displayname))
{
$errors[] = lang("ACCOUNT_DISPLAY_CHAR_LIMIT",array(4,60));
}
if(minMaxRange(4,50,$password) && minMaxRange(4,50,$confirm_pass))
{
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT",array(4,50));
}
else if($password != $confirm_pass)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if(!isValidEmail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
//End data validation
if(count($errors) == 0)
{
//Construct a user object
$user = new User($username,$displayname,$password,$email);
//Checking this flag tells us whether there were any errors such as possible data duplication occured
if(!$user->status)
{
if($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE",array($username));
if($user->displayname_taken) $errors[] = lang("ACCOUNT_DISPLAYNAME_IN_USE",array($displayname));
if($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE",array($email));
}
else
{
//Attempt to add the user to the database, carry out finishing tasks like emailing the user (if required)
if(!$user->userCakeAddUser())
{
if($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if(count($errors) == 0) {
$successes[] = $user->success;
}
}
echo resultBlock($errors,$successes);
$to = 'myemail#domain.com';
$subject = 'New User Signup';
$url = 'mydomain.com/account.php';
$headers .= "From: myemail#domain.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message .= '<html><body>';
$message .= "<p>...message contents...</p>";
mail($to, $subject, $message, $headers);
echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">';
?>
I'm sure it's because I start the email stuff in the wrong place, but when I try to move it elsewhere, I get various errors.
Thanks in advance for any help you can provide.
Wrap your mail code inside like this:
if(count($errors) == 0) {
$to = 'myemail#domain.com';
$subject = 'New User Signup';
$url = 'mydomain.com/account.php';
$headers .= "From: myemail#domain.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message .= '<html><body>';
$message .= "<p>...message contents...</p>";
mail($to, $subject, $message, $headers);
}
Both your if(count($errors) == 0) conditions are doing exactly the same thing. You don't need to add a new condition but remove one. Your script can be simplified like this (pseudocode):
// some processing
// ...
//Forms posted
if(!empty($_POST))
{
// filling $errors[]
//End data validation
if(count($errors) == 0)
{
//Construct a user object
// ...
//Checking this flag tells us whether there were any errors such as possible data duplication occured
// ...
$successes[] = $user->success;
// Send email if no error
// ...
mail($to, $subject, $message, $headers);
}
}
echo resultBlock($errors,$successes);
$url = 'mydomain.com/account.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">';
Related
My PHP code for sending email its working good, but there is a problem that doesn't show who is the sender just show noreply#example.com. I hosted my website at ecowebhosting.
<?php
$error = "";
$successMessage = "";
if ($_POST) {
if (!$_POST["email"]) {
$error .= "An email address is required.<br>";
}
if (!$_POST["message"]) {
$error .= "The message field is required.<br>";
}
if (!$_POST["subject"]) {
$error .= "The subject is required.<br>";
}
if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
$error .= "The email address is invalid.<br>";
}
if ($error != "") {
$error = '<div><p>There were error(s) in your form:</p>' . $error . '</div>';
} else {
$to = "example#gmail.com";
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "MIME-VERSION: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers = "From: ".$_POST['email'] . "\r\n";
$headers = "Reply-To: ".$_POST['email'] . "\r\n";
$headers = "Subject: ".$_POST['subject'] . "\r\n";
$headers = "Message : ".$_POST['message'] . "\r\n";
if (mail($to, $subject, $message, $headers)) {
echo $successMessage = '<div>Your message was sent, we\'ll get back to you ASAP!</div>';
} else {
echo $error = '<div><p><strong>Your message couldn\'t be sent - please try again later</div>';
}
}
}
?>
The sendmail script I have below works on PHP version 5.6.14, but i've had to use the same script on a server that has version 5.3.10 and it just won't send. Do i need to change the syntax of my code to work with older PHP? if so what do i need to change?
<?php
$error = ""; // Initialize error as blank
$errorMsg = ""; // Initialize error as blank
if (isset($_POST['submit'])) { // check if the form is submitted
#### removing extra white spaces & escaping harmful characters ####
$name = trim($_POST['name']);
$email = $_POST['email'];
$phone = $_POST['telephone'];
$company = $_POST['company'];
$message = $_POST['message'];
#### start validating input data ####
#####################################
# Validate First Name #
// if its not alpha numeric, throw error
if (!ctype_alpha(str_replace(array("'", "-"), "",$name))) {
$error .= '<p class="error">Name should be alpha characters only.</p>';
}
// if first_name is not 2-50 characters long, throw error
if (strlen($name) < 2 OR strlen($name) > 50) {
$error .= '<p class="error">Name should be within 2-50 characters long.</p>';
}
# Validate Email #
// if email is invalid, throw error
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // you can also use regex to do same
$error .= '<p class="error">Enter a valid email address.</p>';
}
# Validate Phone #
// if phone is invalid, throw error
if ($phone == "") {
} elseif ($phone != "") {
if (!ctype_digit($phone) OR strlen($phone) != 10) {
$error .= '<p class="error">Enter a valid phone number.</p>';
}
}
# Validate Dealer select #
// if select dealer is empty, throw error
if(empty($messgae))
{
$error .= '<p class="error">Select a subject.</p>';
//$error=true;
}
#### end validating input data ####
#####################################
}
if($name === "" || $email === "" || $subject === ""){
$errorMsg = "Please go back and make sure you have filled out the form correctly";
} else {
if(isset($_POST["name"])) {
// Build the message body
$body .= "Name: ".$_POST["name"]."\n";
$body .= "Email: ".$_POST["email"]."\n";
$body .= "Phone: ".$_POST["telephone"]."\n";
$body .= "Company: ".$_POST["company"]."\n";
$body .= "Subject: ".$_POST["subject"]."\n";
if (isset($_POST['contact'][0])) {
$body .= "Can be contacted by email."."\n";
}
if (isset($_POST['contact'][1])) {
$body .= $_POST["subject"];
}
$body = wordwrap($body, 70);
$subject = $_POST["subject"];
$addr_from = "info#tandsadvertising.co.uk";
require_once('config.php');
/*define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'config.php'); */
$sendmail = mail($addr_to, $subject, $body, "From:" . $addr_from . "\n", "-f" . $addr_from );
if($sendmail) header("Location: /form/thankyou.php");
else { echo "send mail failed, please check settings"; }
}
}
?>
I'm having a difficult time getting my page to redirect after form submission. I've followed the advice that I've been able to find so far and no luck. Any help would be greatly appreciated.
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
$subject = "CONTACT FORM";
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'email#domain.com';
$body = "Name: $name \nEmail: $email";
$headers = 'From: Bond Limo (Newsletter Signup) <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) {
header("Location: http://www.website.com");
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="side-form">
Your header is not being processed. In order for your header to be processed and the redirect to occur, you will have to call the die() function after your header. Like so:
<?php
if(isset($emailSent) && $emailSent) {
header("Location: http://www.website.com");
die();
}
?>
Additionally, your code can be optimized by not checking:<?php if(isset($hasError)) { //If errors are found ?> again. Rather, just connect it with the above if statement and use an else statement like so:
// If there is no error, send the email
if (!isset($hasError)) {
$emailTo = 'email#domain.com';
$body = "Name: $name \nEmail: $email";
$headers = 'From: Bond Limo (Newsletter Signup) <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
$emailSent = mail($emailTo, $subject, $body, $headers);
} else {
// Errors found
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
}
My PHP contact form was recently being used to send spam. Some security measures have since been put in place (please refer to the comments below) and I'm seeking the collective wisdom of others to review the code and to check to make sure it is secure from injection attacks.
Thank you in advance for taking the time to review.
<?php
/* method for validate each input values in case any injection scripts it will ignore */
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
/* honeypot - if hidden field is completed discard form content */
if(!isset($_POST['honeypot']) || $_POST['honeypot'] != '')
{
die("You spammer!\n");
}
else
{
// define variables and set to empty values
$subject = $id = $subcategory = $subcategory = $subcategory_email = $to = $descError = $error =
$remarks = $response= $message= $name = $from = $phone ="";
if(isset($_REQUEST['category']) && $_REQUEST['category']!="")
{
//validate each input values for any injection attacks
$id = test_input($_REQUEST['category']);
$subcategory = test_input($_REQUEST['subcategory']);
$emails = array
(
array("0",""),
array("1","email1#yahoo.com","email2#yahoo.com"),
array("2","email1#yahoo.com","email2#yahoo.com"),
array("3","email1#yahoo.com","email2#yahoo.com"),
array("4","email1#yahoo.com","email2#yahoo.com"),
array("5","email1#yahoo.com","email2#yahoo.com")
);
$value = explode(",", $subcategory);
$subcategory_email = $emails[$id][$value[0]];
$remarks = test_input($_REQUEST['remarks']);
$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #666;" border="1" cellpadding="10">';
$message .= "<tr style='background-color:#F5F5F5;'><th width=25%>Heading </th><th width=75%>Content</th></tr>";
$message .= "<tr><td><b>Category </b></td><td>".$category[$id-1]."</td></tr>";
$message .= "<tr><td><b>SubCategory </b></td><td>".$value[1]."</td></tr>";
$message .= "<tr><td><b>Comments</b></td><td><pre>".$remarks."</pre></td></tr>";
if($response==0)
{
$name = test_input($_REQUEST['name']);
$from = test_input($_REQUEST['email']);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$from))
{
$emailErr = "Invalid email format";
}
$phone = test_input($_REQUEST['phone']);
$message .= "<tr><td><b>Would you like a response? </b></td><td>Yes</td></tr>";
$message .= "<tr><td><b>Name</b></td><td>".$name."</td></tr>";
$message .= "<tr><td><b>E-Mail</b></td><td>".$from."</td></tr>";
$message .= "<tr><td><b>Telephone</b></td><td>".$phone."</td></tr>";
}
else
{
$from = "noreply#test.com";
$message .= "<tr><td><b>Would you like a response? </b></td><td>No</td></tr>";
}
$subject = "SubCategory ".$value[1];
//Normal headers
$headers = "From: " . strip_tags($from) . "\r\n";
$headers .= "Reply-To: ". strip_tags($subcategory_email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message .= "</table>";
if(mail($subcategory_email, $subject, $message, $headers))
{
include("thanks.php");
$error=6;
}
else
{
echo "mail not sent";
}
}
else
{
echo "<br/>";
$subject = "Sub Category";
$to = "Email1#yahoo.com";
if(empty($_REQUEST['remarks']))
{
$descError = "Enter Description";
$error = 5;
}
else
{
$remarks = test_input($_REQUEST['remarks']);
}
if(test_input($_REQUEST['response'])=="0")
{
$yesDIV = "checked";
$response = "Yes";
if(empty($_REQUEST['name']))
{
$nameError = "Name Required";
$error = 5;
}
else
{
$name = test_input($_REQUEST['name']);
}
$from = $_REQUEST['email'];
if(empty($_REQUEST['email']))
{
$emailError = "Email Required";
$error = 5;
}
else if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
$emailError = "Valid Email Required";
$error = 5;
}
}
else
{
$noDIV = "checked";
$response = "No";
$bodyDIV = "style='display:none;'";
}
if($error!=5)
{
$phone = test_input($_REQUEST['phone']);
$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #666;" border="1" cellpadding="10">';
$message .= "<tr style='background-color:#F5F5F5;'><th width=25%>Heading </th><th width=75%>Content</th></tr>";
$message .= "<tr><td><b> Comments</b></td><td ><pre>".$remarks."</pre></td></tr>";
$message .= "<tr><td><b>Would you like a response? </b></td><td>".$response."</td></tr>";
$message .= "<tr><td><b>Name</b></td><td>".$name."</td></tr>";
$message .= "<tr><td><b>E-Mail</b></td><td>".$from."</td></tr>";
$message .= "<tr><td><b>Telephone</b></td><td>".$phone."</td></tr>";
$message .= "</table>";
//Normal headers
$headers = "From: noreply#test.com \r\n";
$headers .= "Reply-To: ". strip_tags($from) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail($to, $subject, $message, $headers))
{
include("thanks.php");
$error=6;
}
else
{
echo "mail not sent";
}
}
}
}
?>
The term "injection" refers to code injection, with code referring to any computer language. Since every computer language is different, the problems and solutions are also different and need to be addressed in a per-language basis. However, you have a generic function that tries to prevent all kind of injections at once and, often, using the worst technique: removing user data.
For instance:
$headers = "From: " . strip_tags($from) . "\r\n";
What sense does it make to take an e-mail address and remove HTML tags from it to compose an e-mail header?
$data = htmlspecialchars($data);
You apply this to e.g. $_REQUEST['email']. Why would you want to insert HTML entities in an e-mail address?
In your code I see two potential sources for injection:
HTML - When you inject user data into HTML you need to ensure that user data is handled as plain text (i.e. whatever the user typed is not rendered as HTML). You can use htmlspecialchars(). You kind of do that but it's really hard to be sure.
E-mail headers - mail()'s fourth argument allows to define mail headers. Injecting raw user input there (which is possibly what's happening now) allows to hide the complete message body, replace it with anything else and even select new recipients. You basically have to strip new lines (again, it's hard to say whether you're doing it right...).
Sending e-mail with PHP is hard. It's better to skip good old mail() and use a third-party library like PHPMailer or Swift Mailer.
I would like to add a failed message re-direct to my mail script, so that if a user enters a wrong address in the email field it gets returned to me, and not to my hosting company's inbox, how do I do that? I've already added return-path but doesn't work, what else can i do to get this code to work.
Here is the code:
<?php if(isset($_POST['submit'])) {
if(trim($_POST['first-name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['first-name']);
}
//Check to make sure that the last name field is not empty
if(trim($_POST['last-name']) == '') {
$hasError = true;
} else {
$lname = trim($_POST['last-name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if(!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure that the phone field is not empty
if(trim($_POST['tel']) == '') {
$hasError = true;
} else {
$phone = trim($_POST['tel']);
}
//Check to make sure that the phone field is not empty
if(trim($_POST['company']) == '') {
$hasError = true;
} else {
$company = trim($_POST['company']);
}
foreach (array($_POST['q1']) as $value) {
$q1 = $value[0];
$q2 = $value[1];
$q3 = $value[2];
}
//If there is no error, send the email
if(!isset($hasError)) {
$to = 'me#host.com';
$recipient = $email;
$subject = 'Subject';
$headers = "From: Me\n" . $to . "\r\n";
$headers .= "Reply-To: ". $to . "\r\n";
$headers .= "Return-Path: ". $to . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$msg1 = "First Message";
$msg2 = "Second Message";
//Send Email
mail($recipient, $subject, $msg2, $headers);
mail($to, $subject, $msg1, $headers);
$emailSent = true;
}
}
?>
the return path is set by the mta based on the envelope sender, you can't just set that in the headers yourself. You can try to set the envelope sender using the $additional_parameters argument of the mail function. See Example #3 on http://www.php.net/manual/en/function.mail.php
In your case, that would be something like
mail($recipient, $subject, $msg2, $headers, "-f $to");
On some systems overriding the envelope sender using -f is restricted. In that case you'd probably have to switch to submitting the mail via SMTP instead of calling the sendmail binary via mail().