Page 3 of 4 FirstFirst 1234 LastLast
Results 21 to 30 of 33

Thread: Confirmation Email PHP Sender

  1. #21
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    Let's back up, just a second.

    PHP Code:
    <?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 Code:
    <?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;

  2. #22
    Join Date
    Feb 2006
    Posts
    223
    Thanks
    7
    Thanked 2 Times in 2 Posts

    Default Try this Validation Code - Tests for valid email address

    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):

    Code:
    // 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:

    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]));
    }
    Then after that, we test all the input, and if there is something we don't like, we send it to the web browser:

    Code:
    // 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.

  3. #23
    Join Date
    Aug 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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 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@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($email0$atIndex);
            
    $localLen strlen($local);
            
    $domainLen strlen($domain);
            if (
    $localLen || $localLen 64) { $isValid false; }                        // local part length exceeded
            
    else if ($domainLen || $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;
    }



     
    ?>

  4. #24
    Join Date
    Aug 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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 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($email0$atIndex);
            
    $localLen strlen($local);
            
    $domainLen strlen($domain);
            if (
    $localLen || $localLen 64) { $isValid false; }                        // local part length exceeded
            
    else if ($domainLen || $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;
    }



     
    ?>

  5. #25
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    PHP Code:
    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.
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  6. #26
    Join Date
    Aug 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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:
    PHP 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.'


  7. #27
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    Quote Originally Posted by djr33 View Post
    PHP Code:
    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() to redirect to an error page, etc..


    Some comments about @Strangeplant's suggestions:
    Quote Originally Posted by Strangeplant View Post
    PHP Code:
    function validEmail($email) {
      
    #  etc. ... 
    Do you have any reason to prefer this function over 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 Code:
    <?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'];
    }
    Quote Originally Posted by Strangeplant View Post
    PHP 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]));
    }
    I very strongly suggest that you always use blocks:
    PHP Code:
    <?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 in your php.ini file instead.
    Last edited by traq; 09-04-2013 at 11:39 PM.

  8. #28
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    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).
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  9. #29
    Join Date
    Aug 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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?

    PHP Code:
    $userEmail filter_var$_POST['email'],FILTER_VALIDATE_EMAIL );

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

    if( ! 
    $userEmail ){

        exit;


  10. #30
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    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.
    Last edited by djr33; 09-09-2013 at 11:42 PM.
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

Similar Threads

  1. Email Auto-Confirmation
    By misslilly1991 in forum PHP
    Replies: 0
    Last Post: 11-08-2011, 10:42 PM
  2. Adding a confirmation email?
    By Bengal313 in forum PHP
    Replies: 2
    Last Post: 08-05-2010, 06:53 PM
  3. php email confirmation...
    By lirhahs in forum PHP
    Replies: 15
    Last Post: 06-10-2010, 09:27 AM
  4. Simple Email Confirmation/OR cc form
    By almcaffee in forum JavaScript
    Replies: 2
    Last Post: 12-08-2009, 01:27 PM
  5. Sending email confirmation
    By Tayfun in forum PHP
    Replies: 4
    Last Post: 08-12-2009, 08:37 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •