Log in

View Full Version : Confirmation Email PHP Sender



itskater
08-21-2013, 07:02 PM
Hello,
I am trying to get this form to send a confirmation email to the user saying thank you and some other things but I can not get it to send the email to the user only me. Here is the php code:


<?php

//print "this is the last record";
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "info@mywebsite.com";
$email_subject = "Registration";

$email_message .= "First Name Entered: ".$_GET["fname"]."\n";
$email_message .= "Last Name Entered: ".$_GET["lname"]."\n";
$email_message .= "Email Entered: ".$_GET["email"]."\n";
$email_message .= "Invitation Code: ".$_GET["email1"]."\n";

$ip=$_SERVER['REMOTE_ADDR'];


$email_message .= "IP ADDRESS: ". $ip."\n";
$ip=$_ENV['REMOTE_ADDR'];






// create email headers
$headers = 'From: '.$_GET["email"]."\r\n".
'Reply-To: '.$_GET["email"]."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

//NEW\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//Create the variables to be used in the mail
$to=$_POST['email'];
$subject="Email Confirmation";
$message="This is a confirmation email";
//Use the mail function to send the confirmation email
mail($to,$subject,$message);

//print $_GET["email"];
//print "it worked";
die();


?>

Thank you

itskater
08-21-2013, 07:49 PM
I have since changed the code to:


<?php


$email_to = "info@codeevents.com";
$email_subject = "VIP Member Registration";

$email_message .= "First Name Entered: ".$_GET["fname"]."\n";

$email_message .= "Last Name Entered: ".$_GET["lname"]."\n";

$email_message .= "Email Entered: ".$_GET["email"]."\n";

$email_message .= "Invitation Code: ".$_GET["email1"]."\n";

$ip=$_SERVER['REMOTE_ADDR'];

$email_message .= "IP ADDRESS: ". $ip."\n";

$ip=$_ENV['REMOTE_ADDR'];

$to=$_POST['email'];

$subject="Email Confirmation";

$message="This is a confirmation email";

$subject .= "Test Email"."\n";

$email .= "Email Entered: ".$_GET["email"]."\n";

$sendto = $_POST['email']."\n";




//email headers
$headers = 'From: '.$_GET["email"]."\r\n".
'Reply-To: '.$_GET["email"]."\r\n" .
'X-Mailer: PHP/' . phpversion();


@mail($email_to, $email_subject, $email_message, $headers);


@mail($sendto, $subject, $message);


die();


?>

itskater
08-28-2013, 11:11 PM
Any help please.

djr33
08-28-2013, 11:17 PM
Can you explain a little more about this?

1. Have you looked at various tutorials available around the internet? They can guide you through this step by step.

2. Do you know PHP fairly well? It looks to me like this is just a matter of lining up the variables in the right places. When you see PHP, does it look like a foreign, unapproachable language? Do you want help with the basics? Or is this problem more complicated than I'm seeing? Do you know how to, for example, set $x=$y, so that you could copy one value to a new one?

3. a) Who receives the email now?
b) Who do you want to receive the email instead?
c) How do you want to determine that value?

fastsol1
08-29-2013, 04:11 PM
This line is a issue.

$sendto = $_POST['email']."\n";
You are using $_GET on all other vars but this one, plus you are adding on the \n which will not be valid for a email address.

itskater
08-29-2013, 07:56 PM
Hello,
I am trying to make this contact form send an confirmation email to the user just saying thank you for registering. I have tried several ways and can not get it to work. It always sends me an email but nothing to the users email.

This is the PHP sender file code I have been trying to set up:


<?php


$email_to = "info@mywebsite.com";
$email_subject = "Registration";

$email_message .= "First Name Entered: ".$_GET["fname"]."\n";






$email_message .= "Last Name Entered: ".$_GET["lname"]."\n";






$email_message .= "Email Entered: ".$_GET["email"]."\n";






$email_message .= "Invitation Code: ".$_GET["email1"]."\n";





$ip=$_SERVER['REMOTE_ADDR'];

$email_message .= "IP ADDRESS: ". $ip."\n";







$ip=$_ENV['REMOTE_ADDR'];



$to=$_POST['email'];

$subject="Email Confirmation";




$message="This is a confirmation email";






$subject .= "Test Email"."\n";






$email .= "Email Entered: ".$_GET["email"]."\n";



$sendto = $_POST['email']."\n";




//email headers
$headers = 'From: '.$_GET["email"]."\r\n".
'Reply-To: '.$_GET["email"]."\r\n" .
'X-Mailer: PHP/' . phpversion();


@mail($email_to, $email_subject, $email_message, $headers);


@mail($sendto, $subject, $message);


die();


?>



Thank you

fastsol1
08-29-2013, 09:08 PM
did you even read my last post?

itskater
08-29-2013, 10:12 PM
Hello Fastsol1 and Djr33,

I have tried your advice without any luck. I changed the code from POST to GET but it still does the same thing. It will send me the info perfectly how I want it to but the confirmation email does not send at all. I have been looking up tutorials and trying them all without luck. All I want is the email that is entered into the field to be sent an email from me that says thank you for registering.

Here is the current code:


<?php


$email_to = "info@mywebsite.com";
$email_subject = "Registration";

$email_message .= "First Name Entered: ".$_GET["fname"]."\n";

$email_message .= "Last Name Entered: ".$_GET["lname"]."\n";

$email_message .= "Email Entered: ".$_GET["email"]."\n";

$email_message .= "Invitation Code: ".$_GET["email1"]."\n";

$ip=$_SERVER['REMOTE_ADDR'];

$email_message .= "IP ADDRESS: ". $ip."\n";

$ip=$_ENV['REMOTE_ADDR'];

$to=$_POST['email'];

$subject="Email Confirmation";

$message="This is a confirmation email";

$subject .= "Test Email"."\n";

$email .= "Email Entered: ".$_GET["email"]."\n";

$sendto = $_GET['email'];




//email headers
$headers = 'From: '.$_GET["email"]."\r\n".
'Reply-To: '.$_GET["email"]."\r\n" .
'X-Mailer: PHP/' . phpversion();


@mail($email_to, $email_subject, $email_message, $headers);


@mail($sendto, $subject, $message);


die();


?>

djr33
08-29-2013, 10:29 PM
Please refer back to my previous message and the questions there. It's very difficult to help someone when it requires a lot of guessing from us about what's actually going on.

What I would recommend, if this is intended as a learning experience, would be creating a new, blank document and retyping everything-- go through each line to see what it does and if it is necessary and whether anything is incorrect. The result will be cleaner.
If, on the other hand, you just want something that works, I'd suggest looking for a tutorial with working code (there are some out there) and starting from that. This has some confusing issues of what variable is used when (some don't seem to be doing anything).

Another idea: print this out and draw arrows to see where all of the text is going.

And another: print out (using 'echo') all of the information going into mail().

And: turn off the error suppression (@) before the mail() function. If you get an error, that's a good thing-- you should see what it says. You *might* want to turn it back on if you might be getting bad input from users later (though there are probably better ways to handle that).

traq
08-30-2013, 02:13 PM
Generally speaking, this is very straightforward:

1. find the name of the form field where the user enters their email
2. validate that the value in it is a single, valid email address
3. put that value in the first param of the mail function.

If you're having as much trouble as you say, I would suggest following Daniel's advice and starting over with a "clean slate." This way, you can eliminate any minor problems that might exist from previous (nonworking) attempts to fix it, and your code will be easier for you to understand and follow.

Strangeplant
09-03-2013, 01:44 PM
Well, I see that it is the second email that is failing; the first gets through. The second email call does not have the variable '$headers', and therefore no 'from' in the email function, so it will NEVER be sent (unless you have an override in php.ini, and I don't think you do.) Why don't you read-up on the php mail function first? See: http://php.net/manual/en/function.mail.php And, BTW, you have some unused variables in your script. There is no validation, as mentioned before by the moderators. There are dozens of more advanced scripts on the web, so after you get this running, put in all the basics about field validation.

itskater
09-03-2013, 09:00 PM
Hello,
I have been trying to make a basic form with a First Name, Last Name, Email, and Invitation Code fields. Then once the submit button has been clicked it will send me the info they entered and there email will get a "Thank you" email. The main problem with this is the template that I am using, It doesn't want to work with random codes. I was using a very confusing Ajax / JS way to make the email send but no luck with the confirmation. So I am starting from scratch and seeing that I cant seem to find any help online about confirmations I though I would ask here. I want to keep it basic so I can easily edit the code for other forms that I may need. The template is in HTML but the index page is linked to every other HTML page using the code in the index.html file head tag for every HTML page.

Here is the template that I am using:

http://www.renklibeyaz.com/rightnow/ (http://www.renklibeyaz.com/rightnow/)

Thank you and any help is much appreciated.

itskater
09-03-2013, 09:48 PM
I am currently trying to use this code but it wont send the info just he subject names.

Form:

<form name="htmlform" method="post" action="send.php">
<table width="450px">
</tr>
<tr>
<td valign="top">
<label for="fname">First Name:</label></td>
<td valign="top">
<input type="text" name="fname" maxlength="50" size="30">
</td>
</tr>

<tr>
<td valign="top">
<label for="lname">Last Name: </label>
</td>
<td valign="top">
<input type="text" name="lname" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address: </label></td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
</td>

</tr>
<tr>
<td valign="top">
<label for="email1">Invitation Code:</label></td>
<td valign="top">
<input type="text" name="email1" maxlength="30" size="30">
</td>
</tr>

<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Register">
</td>
</tr>
</table>
</form>


Send.php file:

<?php




$ip=$_SERVER['REMOTE_ADDR'];
$email_to = "info@mywebsite.com";
$email_subject = "Registration";




$email_message .= "First Name Entered: ".$_POST["fname"]."\n";




$email_message .= "Last Name Entered: ".$_POST["lname"]."\n";




$email_message .= "Email Entered: ".$_POST["email"]."\n";




$email_message .= "Invitation Code: ".$_POST["email1"]."\n";














//email headers




$headers = 'From: '.$_POST["email"]."\r\n".




'Reply-To: '.$_POST["email"]."\r\n" .




'X-Mailer: PHP/' . phpversion();




echo (mail($email_to, $email_subject, $email_message, $headers) ? "Sent to mywebsite": "failed sending to website");

echo (mail($email_to, $email_subject, $email_message, $headers) ? "Sent to mywebsite": "failed sending to website");



die();
?>

james438
09-03-2013, 10:02 PM
itskater, it is good to start a new thread when you have a separate question that does not quite relate to your current problem, but it is not necessary to create new thread to post new developments in your current project. If I am misunderstanding why you are creating new threads please let me know.

itskater
09-03-2013, 10:15 PM
Thank you. That is the updated code, I'm just working on the confirmation now. I think you guys can help now since that other code was confusing since it was linking to so many other different codes and languages. Now it is just HTML and PHP.

itskater
09-03-2013, 10:49 PM
So I guess my final question is... How can I edit this code so that it will send a second email to the "email" associated with this code

$email_message .= "Email Entered: ".$_POST["email"]."\n";
Also in the email subject to say "Thank you" and then in the Body of the email say "Thank you for registering"
Do I need to enter in a second set of $headers? or maybe duplicate the whole <?php tag? I'm assuming I'm almost there just a small twitch to get it to work.

Thank you to everyone helping.

___________________________________________________________________________________

I am so close! :mad:

I can get the email to send to my email and another exactly how I want but I can not set it up so that the other email is the email that the user entered. I set it so that it was my email for the first one and another email I have for the second and received both. But I don't know how to make it so that the email entered is the email that will receive the Thank you email.


<?php




$ip=$_SERVER['REMOTE_ADDR'];
$email_to = "info@mywebsite.com";
$email_subject = "Registration";




$email_message .= "First Name Entered: ".$_POST["fname"]."\n";




$email_message .= "Last Name Entered: ".$_POST["lname"]."\n";




$email_message .= "Email Entered: ".$_POST["email"]."\n";




$email_message .= "Invitation Code: ".$_POST["email1"]."\n";


//email headers




$headers = 'From: '.$_POST["email"]."\r\n".

'Reply-To: '.$_POST["email"]."\r\n" .

'X-Mailer: PHP/' . phpversion();




echo (mail($email_to, $email_subject, $email_message, $headers) ? "Sent":"Fail");









$ip=$_SERVER['REMOTE_ADDR'];
$email_to = "me@myemail2.com";
$email_subject = "Thank you | Code Events";

$email_message1 = "Thank you!";



//email headers




$headers = 'From: '.$_POST["email"]."\r\n".

'Reply-To: '.$_POST["email"]."\r\n" .

'X-Mailer: PHP/' . phpversion();




echo (mail($email_to, $email_subject, $email_message1, $headers) ? "Sent":"Fail");





die();



?>

djr33
09-03-2013, 11:07 PM
You should look at the documentation for mail() (http://php.net/manual/en/function.mail.php). Since you know what parameters are required (the email address, the text, etc.), you should be able to just fill those into that function as needed. Simply add that as a new line in the code, with the right arguments, and it will send another email. There's nothing magical about sending email in PHP, although it does need a little set up before you can send the email (such as where you're sending it). If you don't need any dynamic (changing/user-input) values, you can just use a single line with all of the information as text, and that will work.

Again, you haven't addressed my earlier questions, including about your experience with PHP-- so I don't know if I need to explain in a lot of detail (for example, you might have no idea what a "function" is) or just outline in general terms because you can figure out the rest. It isn't a problem either way-- you might know just the basics, or you might know a lot. But either way, knowing that will help me to help you...



By the way, you still don't seem to be using any kind of email address verification (as traq suggested above). That's a very bad idea, but it's up to you. (The consequences can range from errors when processing the script to even having your server blacklisted for sending emails, because too many of your attempted emails are not reaching a destination.)
One simple way to validate an email address is:
http://php.net/manual/en/function.filter-var.php

itskater
09-03-2013, 11:17 PM
Hello djr33,
I know HTML very well but PHP I am still learning. I know the basics and how to usually get things to work like I want. I did research the mail() function and I see how to use it but the final question I am asking I couldn't find online. Can I use a code to take this code entry:

$email_message .= "Email Entered: ".$_POST["email"]."\n";


and automatically put the entry into where it says "me@myemail.com"

$email_to = "me@myemail.com";

I think I need to some how associate it to the "email' but I can not find a helpful code. I will try and add the verification after I have successfully added the confirmation.

Thank you.

itskater
09-03-2013, 11:28 PM
RESOLVED!

Here is the code:

$email_to = $_POST["email"];

djr33
09-04-2013, 12:19 AM
You can use $_POST['X'] anywhere you can use $X, so it's up to you how you want to arrange it.

Something like this would work:
mail($_POST['X'],'Hello','Body text...',$headers);

I'd suggest reading through the code a lot more carefully to understand what each part does. The structure of PHP is not very complicated, and once you understand things like functions and arguments you'll be able to do a lot more with the code. (I'm not complaining that you're still learning-- that's good, there's a lot to learn, but you'll get there.)

traq
09-04-2013, 01:47 AM
Let's back up, just a second.


<?php
// . . .
$headers = 'From: '.$_POST["email"]."\r\n";
// . . .
$email_to = $_POST["email"];
Both of these lines (as an example, others need attention as well) have the same problem: you're taking user-submitted data and using it without doing any validation. In almost all cases, this opens your code up to a lot of potential errors. In most cases (including this one), it also creates security holes.

In this case, your form has a field named email. You expect the user to enter their email address there, so you can reply to their message and send them a confirmation.

Possible error:
The user misreads the instructions:

Please enter your email address: [hi, my name is Bob]

Possible exploit:
The user enters multiple email addresses, separated by newlines:

Please enter your email address: [someguy@example.com
another@example.net
and-so-on@and-so-forth]

In the first case, you might say "no harm; it's their own fault anyway." Right? Maybe. But you've wasted everyone's time, and maybe lost an interested customer.

In the second case, you've become a spam server. You might unwittingly be helping commit XSRF or phishing attacks. Just as significantly, when ISPs look for someone to crack down on for this behavior, it's going to be you.

In both cases, the solution is simple: validate all user input. Everything from $_GET, $_POST, $_FILES, $_COOKIE, and $_REQUEST (and some of the $_SERVER vars, in fact) come from the user. You cannot trust any of it. Always make sure you are getting the information you expect.

So, $_POST['email'] is supposed to be a single email address. Check to be sure!
<?php

# <http://php.net/filter_var/>
# this will return the value from $_POST['email'] _IF_ it is a correctly formed email address,
# or FALSE if it is not.
# (email addresses can't have newlines in them, so multiple emails will also fail.)
$userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL );

if( ! $userEmail ){
/* not a properly formatted email address - show the user an error */
exit;
}

// otherwise, you're good to go.
$headers = "From: $userEmail\r\n";
// . . .
$email_to = $userEmail;

Strangeplant
09-04-2013, 05:35 PM
Here is a php function that you can use for validation in your script - place it at the bottom (There are others, of course, and I may have gotten some or all of it from Ilovejackdaniels.com):


// check to see if email is valid
function validEmail($email) {
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) { $isValid = false; }
else {
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) { $isValid = false; } // local part length exceeded
else if ($domainLen < 1 || $domainLen > 255) { $isValid = false; } // domain part length exceeded
else if ($local[0] == '.' || $local[$localLen-1] == '.') { $isValid = false; } // local part starts or ends with '.'
else if (preg_match('/\\.\\./', $local)) { $isValid = false; } // local part has two consecutive dots
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { $isValid = false; } // character not valid in domain part
else if (preg_match('/\\.\\./', $domain)) { $isValid = false; } // domain part has two consecutive dots
else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
// character not valid in local part unless local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; }
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { $isValid = false; } // domain not found in DNS
}
return $isValid;
}

You use it something like this, so at the top of your php script that gets the data from the html page, it should have:


<?php

// first clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);

$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

Then after that, we test all the input, and if there is something we don't like, we send it to the web browser:


// test input values for errors
$errors = array();
if(strlen($name) < 2) {
if(!$name) { $errors[] = "You must enter a name."; }
else { $errors[] = "Name must be at least 2 characters."; }
}
if(!$email) { $errors[] = "You must enter an email."; }
else if (!validEmail($email)) { $errors[] = "You must enter a valid email."; }

if($errors) {
// output errors to browser and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>");
}


Then, since everything looks good, we can finally send the email! So send it here.

itskater
09-04-2013, 06:39 PM
Thank you guys so much!
Here is the current code with the validation. The only problem is when the email is sent it will take you to send.php that will say "Thank you, your email was sent successfully!" if it sent, but when failed it is a blank white page with no text. Also the error codes are not showing up it just shows a blank page. I know I can add HTML to the send() tag but when I add the <html><head><body>hello</body></head></html> but it shows the whole code not the formatted way. Is this normal?

Thanks guys


<?php

// first clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);

$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}




$ip=$_SERVER['REMOTE_ADDR'];
$email_to = "info@codeevents.com";
$email_subject = "Registration OC TEST";




$email_message .= "First Name Entered: ".$_POST["fname"]."\n";




$email_message .= "Last Name Entered: ".$_POST["lname"]."\n";




$email_message .= "Email Entered: ".$_POST["email"]."\n";

$userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL );

if( ! $userEmail ){

exit;
}




$email_message .= "Invitation Code: ".$_POST["email1"]."\n";


//email headers




$headers = 'From: '.$_POST["email"]."\r\n".

'Reply-To: '.$_POST["email"]."\r\n" .

'X-Mailer: PHP/' . phpversion();




echo (mail($email_to, $email_subject, $email_message, $headers) ? "Thank you, your email was sent successfully!":"We're sorry, something went wrong.");









$ip=$_SERVER['REMOTE_ADDR'];
$email_to = $_POST["email"];
$email_subject = "Thank you | Code Events";

$email_message1 = "Thank you for registering with Code Events!";



//email headers




$headers = 'From: '.$_POST["email"]."\r\n".

'Reply-To: '.$_POST["email"]."\r\n" .

'X-Mailer: PHP/' . phpversion();




echo (mail($email_to, $email_subject, $email_message1, $headers) ? "":"");




die();





// test input values for errors
$errors = array();
if(strlen($fname) < 2) {
if(!$fname) { $errors[] = "You must enter a name."; }
else { $errors[] = "Name must be at least 2 characters."; }
}
if(!$email) { $errors[] = "You must enter an email."; }
else if (!validEmail($email)) { $errors[] = "You must enter a valid email."; }

if($errors) {
// output errors to browser and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>");
}




// check to see if email is valid
function validEmail($email) {
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) { $isValid = false; }
else {
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) { $isValid = false; } // local part length exceeded
else if ($domainLen < 1 || $domainLen > 255) { $isValid = false; } // domain part length exceeded
else if ($local[0] == '.' || $local[$localLen-1] == '.') { $isValid = false; } // local part starts or ends with '.'
else if (preg_match('/\\.\\./', $local)) { $isValid = false; } // local part has two consecutive dots
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { $isValid = false; } // character not valid in domain part
else if (preg_match('/\\.\\./', $domain)) { $isValid = false; } // domain part has two consecutive dots
else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
// character not valid in local part unless local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; }
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { $isValid = false; } // domain not found in DNS
}
return $isValid;
}



?>

itskater
09-04-2013, 09:56 PM
Hey guys,
One last question, the whole form seems to be working correctly except when it fails. When it fails it just shows a blank white page and does nothing. When it passes it shows a basic HTML page then redirects to the home page. How can I set this up so when the form fails it says "We're sorry something went wrong, go click here to go back" or show the actual reason why it failed, like "please enter an email".

Here is the code:

<?php

// first clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);

$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}




$ip=$_SERVER['REMOTE_ADDR'];
$email_to = "info@mywebsite.com";
$email_subject = "Registration";




$email_message .= "First Name Entered: ".$_POST["fname"]."\n";




$email_message .= "Last Name Entered: ".$_POST["lname"]."\n";




$email_message .= "Email Entered: ".$_POST["email"]."\n";

$userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL );

if( ! $userEmail ){

exit;
}




$email_message .= "Invitation Code: ".$_POST["email1"]."\n";


//email headers




$headers = 'From: '.$_POST["email"]."\r\n".

'Reply-To: '.$_POST["email"]."\r\n" .

'X-Mailer: PHP/' . phpversion();




echo (mail($email_to, $email_subject, $email_message, $headers) ? "<html><head><meta http-equiv='Refresh' content='1; url=http://www.mywebsite.com/oc'></head><body bgcolor='#000000'><center><br><br><h3><font color='white'>Thank you, you have successfully registered!</font></h3></center></html>
":"<html><body bgcolor='#000000'><center><font color='white'><h2>We're sorry, something went wrong.</h2></font><p><font color='white'>Please return to <a href='http://www.mywebsite.com'>Home</a>.</font></p></center></body></html>");



$ip=$_SERVER['REMOTE_ADDR'];
$email_to = $_POST["email"];
$email_subject = "Thank you";

$email_message1 = "Thank you for registering";



//email headers




$headers = 'From: '.$_POST["email"]."\r\n".

'Reply-To: '.$_POST["email"]."\r\n" .

'X-Mailer: PHP/' . phpversion();




echo (mail($email_to, $email_subject, $email_message1, $headers) ? "":"");




die();





// test input values for errors
$errors = array();
if(strlen($fname) < 2) {
if(!$fname) { $errors[] = "You must enter a name."; }
else { $errors[] = "Name must be at least 2 characters."; }
}
if(!$email) { $errors[] = "You must enter an email."; }
else if (!validEmail($email)) { $errors[] = "You must enter a valid email."; }

if($errors) {
// output errors to browser and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>");
}




// check to see if email is valid
function validEmail($email) {
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) { $isValid = false; }
else {
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) { $isValid = false; } // local part length exceeded
else if ($domainLen < 1 || $domainLen > 255) { $isValid = false; } // domain part length exceeded
else if ($local[0] == '.' || $local[$localLen-1] == '.') { $isValid = false; } // local part starts or ends with '.'
else if (preg_match('/\\.\\./', $local)) { $isValid = false; } // local part has two consecutive dots
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { $isValid = false; } // character not valid in domain part
else if (preg_match('/\\.\\./', $domain)) { $isValid = false; } // domain part has two consecutive dots
else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
// character not valid in local part unless local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; }
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { $isValid = false; } // domain not found in DNS
}
return $isValid;
}



?>

djr33
09-04-2013, 11:02 PM
if( ! $userEmail ){

exit;
}


"If the email address is invalid, exit the script [and therefore leave a blank page]..."

Instead, use echo 'Hello World!'; to do whatever you'd like.

itskater
09-04-2013, 11:25 PM
Thank you,
I have tried switching the code but when using echo it will always show successfully sent even if the email is left blank, if you enter "hgldsfg" it will not send the email but still says successfully sent. I understand that the exit tag is making it go to a white screen but how can I get it to show that message.

Here is the new code:

$email_message .= "Email Entered: ".$_POST["email"]."\n";

$userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL );



echo 'Were sorry, something went wrong.
Please go back.';

traq
09-04-2013, 11:29 PM
if( ! $userEmail ){

exit;
}


"If the email address is invalid, exit the script [and therefore leave a blank page]..."

Instead, use echo 'Hello World!'; to do whatever you'd like.
Quite right. The exit is there to stop the script from continuing after you present whatever error message to the user - maybe by adding some code there, or using header() (http://php.net/header/) to redirect to an error page, etc..


Some comments about @Strangeplant's suggestions:


function validEmail($email) {
# etc. ...
Do you have any reason to prefer this function over filter_var() (http://php.net/filter_var)? The latter (being an internal PHP function) is much faster, immediately available, and maintained by the PHP team. The only feature it lacks is requiring a TLD in the domain part (which is not really a flaw, since valid email addresses don't necessarily require a TLD). Logically, you need one in order to reach an email address over the internet, but you can enforce that by changing your check to something like:
<?php

if( ! filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL ) || ! preg_match( '#\.[\w]{2,}$#i',$_POST['email'] ) ){
/* email address is not valid, or does not contain a TLD (and is therefore unreachable over the internet) */
}
else{
$userEmail = $_POST['email'];
}



<?php

// first clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);

$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

I very strongly suggest that you always use blocks:

<?php

if( something )
print "NO!";

if( somethingelse ){
print "yes!";
}Leaving the brackets off "works" for single-line statements (technically, and depending on the circumstances, if you're very careful about it), but it often leads to fragile code and debugging nightmares.

Second, while there are some circumstances where it will be necessary to manually strip slashes, it is always better (and usually easier) to turn off magic_quotes_gpc (http://php.net/magic_quotes_gpc) in your php.ini file instead.

djr33
09-05-2013, 02:19 AM
Quite right. The exit is there to stop the script from continuing after you present whatever error message to the user - maybe by adding some code there, or using header() to redirect to an error page, etc..Oops. Right. itskater, you still need some way to disable the rest of the page from executing.

You should use if statements, redirects, or something else. Or, you can keep "exit" after the echo. But in general "exit" is a bad option (because it's not usually the way you want to organize code, for reasons beyond what is relevant here).

itskater
09-09-2013, 11:29 PM
Thank you guys,
Is there anyway to use a different code then exit? If I use echo then exit it shows the echo notice event if it was successful. How can I make it show the failure notice?


$userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL );

echo 'Were sorry, something went wrong.
Please go back.';

if( ! $userEmail ){

exit;
}

djr33
09-09-2013, 11:36 PM
Organize your code into if-blocks. The "echo" should go within the if-block there, and then it will only show if (condition-is-met).

You should try to read your code line by line to see what it does. If you're guessing while coding, you certainly are going to do something wrong. If you understand what each line does, then it's just a slight extension to see how it fits together. Sometimes when I was learning to do that (such as editing a complicated existing script) I would actually print it out to read it and write notes on it. (I still do that, though rarely, for really complicated code.)

Edit: to add to that, I also, when the code is complex, make a point of commenting every single line so I know what it means. You can try that too.

traq
09-10-2013, 03:43 AM
Thank you guys,
Is there anyway to use a different code then exit? If I use echo then exit it shows the echo notice event if it was successful. How can I make it show the failure notice?


$userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL );

echo 'Were sorry, something went wrong.
Please go back.';

if( ! $userEmail ){

exit;
}

The notice needs to be in the same block as the exit command - after all, you only want to tell them "something went wrong" if something went wrong.


$userEmail = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL );

if( ! $userEmail ){
// something went wrong.

// tell the user.
echo 'Were sorry, something went wrong.
Please go back.';

// make the script end here.
exit;
}
I would suggest something more useful than "Please go back" - send them to an actual error page, for example, or show them the form again (with error message(s) included). It's a little more complicated to set up, but it's a lot nicer for all concerned.

For example:
if( ! $userEmail ){
header( "Location: http://example.com/contact-page-with-error-message.php" );
exit;
}

Deadweight
09-12-2013, 08:10 PM
Fyi you will need to set up a SMTP if you haven't set one up.

traq
09-12-2013, 09:28 PM
Fyi you will need to set up a SMTP if you haven't set one up.

Please read through the entire thread before replying. The OP is using PHP's mail() function, which simply uses whatever mail program the host enables (usually sendmail). An SMTP server or account is not required (in fact, SMTP is generally not even supported).