SitePoint Sponsor

User Tag List

Results 1 to 23 of 23
  1. #1
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Reply to mail form not working properly

    When users press the submit button, I receive an email giving me the result of an online test, but the problem is that I dont receive their email address or name:
    This is the php:
    Code:
    	// Mail things
    
    <?php
    
    	
    function valid_email($address)
    {
    	// check an email address is possibly valid
    	if (ereg('^[a-zA-Z0-9 \._\-]+@([a-zA-z0-9\-]*\.)+[a-zA-Z]+$',$address))
    	{
    		return true;
    	}
    	return false;
    }
    
    
    
    $to = "myname@hotmail.com"; 
    $subject = "Someone scored ". $score . " over ". $scoremax . "."; 
    $headers  = "MIME-Version: 1.0 \r\n" ; 
    $headers .= "Content-Type: text/plain \r\n"; 
    $headers .= "Cc: \r\n"; 
    $headers .= "From: <Webmaster@mysite.com> \r\n\r\n"; 
    $message = "From: ".$visitormail."\n\n"; 
    
    
    
    mail($to, $subject, $message, $headers); 
    
    
    
    
    //new code below
    
    // Somewhere in the backend or something
    function generateSubmitKey()
    {
        // Generate key
        $_SESSION["submit_key"] = md5(rand() . $_SERVER["REMOTE_ADDR"] . rand() . date("dmYHis") . microtime());
    
        // Generate random name for using with submit button name, so bot's can't be easily be reading a standard name for it.
        // I'm also trying to make it regexp scan proof.
        $_SESSION["submit_rand_name"] = md5(rand() . 'submit_button' . rand() . microtime());
    }
    
    function checkSubmitKey()
    {
        if (!isset($_SESSION["submit_key"]))
        {
            // We don't use the key so return always true
            return true;
        }
    
        if (!isset($_POST[$_SESSION["submit_rand_name"]]))
        {
            // The value doesn't exists, but the key does
            // This seems like a spam post to me
            return false;
        }
    
        if ($_POST[$_SESSION["submit_rand_name"]] == $_SESSION["submit_key"])
        {
            return true;
        }
    
        // Shouln't come here, if it does, the key isn't correct
        return false;
    }
    //above new code
    
    //other code
    
    // In the backend
    function getInput()
    {
        if (isset($_POST[$_SESSION["content_rand_name"]]) && !empty($_POST[$_SESSION["content_rand_name"]]))
        {
            $content = $_POST[$_SESSION["content_rand_name"]];
            
            // do something with the content
        }
    }
    
    //other code above
    
    	?>
    and this is the html part:

    Code:
    <form action="result.php" method="post" id="form_id">
    
    (online test here)
    
    
    Your Name: <input type="text" name="name">&nbsp;&nbsp;&nbsp;
    <em> *</em>E-mail: <input type="text" name = "mail"><br><br><br/>
    
    
    
    <input type="submit" value="Submit Test">
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type=reset value=Clear>
    
    </form>
    Any help greatly appreciated. Thank you.

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    You appear to have a typo, try passing $headers to your mail call rather than $header.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    sorry...could you explain how to do that?

  4. #4
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    I would have, but you've edited your post.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  5. #5
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Smile

    Yes I just edited out a couple of lines that I had inserted, but which didnt work, so I deleted them again, hoping that someone on this forum might know more than me...which wouldn't be difficult.

  6. #6
    SitePoint Addict
    Join Date
    Jul 2008
    Posts
    213
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your form fields are named 'name' and 'mail', but I don't see those variables anywhere in your code. I see you have $visitormail, but where does that get its value from?

    Also, you may want to consider using another field name instead of 'mail'. It may be a little less confusing since the name is being used for the PHP function. Just a suggestion.

  7. #7
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Do you receive any email at all?
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  8. #8
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    When users press the submit button, I receive an email giving me the result of an online test, but the problem is that I dont receive their email address or name....yea I did think the $visitormail shouldnt be there..I should have called ot $mail...now I'm trying to implement some of your helpful suggestions..but I only have a dial up connection so it's a bit slow...

  9. #9
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    so sorry for the confusion....
    I only get the reply email with the result of the online test, but without the person's name or email when I use the following php:

    [code]
    // Mail things



    function valid_email($address)
    {
    // check an email address is possibly valid
    if (ereg('^[a-zA-Z0-9 \._\-]+@([a-zA-z0-9\-]*\.)+[a-zA-Z]+$',$address))
    {
    return true;
    }
    return false;
    }



    $to = "mymail@hotmail.com";
    $subject = "Someone scored ". $score . " over ". $scoremax . ".";
    $headers = "MIME-Version: 1.0 \r\n" ;
    $headers .= "Content-Type: text/plain \r\n";
    $headers .= "Cc: \r\n";
    $headers .= "From: <Webmaster@mysite.com> \r\n\r\n";
    $message = "From: ".$mail."\n\n";


    $retval = mail ($to,$subject,$message,$header);
    if( $retval == true )
    {
    echo "Message sent successfully...";
    }
    else
    {
    echo "Message could not be sent...";
    }







    //new code below

    // Somewhere in the backend or something
    function generateSubmitKey()
    {
    // Generate key
    $_SESSION["submit_key"] = md5(rand() . $_SERVER["REMOTE_ADDR"] . rand() . date("dmYHis") . microtime());

    // Generate random name for using with submit button name, so bot's can't be easily be reading a standard name for it.
    // I'm also trying to make it regexp scan proof.
    $_SESSION["submit_rand_name"] = md5(rand() . 'submit_button' . rand() . microtime());
    }

    function checkSubmitKey()
    {
    if (!isset($_SESSION["submit_key"]))
    {
    // We don't use the key so return always true
    return true;
    }

    if (!isset($_POST[$_SESSION["submit_rand_name"]]))
    {
    // The value doesn't exists, but the key does
    // This seems like a spam post to me
    return false;
    }

    if ($_POST[$_SESSION["submit_rand_name"]] == $_SESSION["submit_key"])
    {
    return true;
    }

    // Shouln't come here, if it does, the key isn't correct
    return false;
    }
    //above new code

    //other code

    // In the backend
    function getInput()
    {
    if (isset($_POST[$_SESSION["content_rand_name"]]) && !empty($_POST[$_SESSION["content_rand_name"]]))
    {
    $content = $_POST[$_SESSION["content_rand_name"]];

    // do something with the content
    }
    }

    //other code above


    ?>

  10. #10
    SitePoint Addict
    Join Date
    Jul 2008
    Posts
    213
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As SilverBulletUK mentioned in his first response, you have a typing mistake in the line below. It is missing the letter 's' in $header, which I added in the code below.

    PHP Code:
    if( mail($to,$subject,$message,$headers) ) 

  11. #11
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't think adding the "s" to $header fixed the problem, but I'm a bit confused after all the changes so I'm looking for a different anti spam code now...
    Thanks for the help anyway...

  12. #12
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    sorry I'm back again... I can't figure out why now I don't receive ANY email reply to my php form. Can you see any reason?

    this is the relevant php code:
    Code:
    $to = "myname@hotmail.com, othername@hotmail.com"; 
    $subject = "Someone scored ". $score . " over ". $scoremax . "."; 
    $headers  = "MIME-Version: 1.0 \r\n" ; 
    $headers .= "Content-Type: text/plain \r\n"; 
    $headers .= "Cc: \r\n"; 
    $headers .= "From: <Webmaster@mysite.com> \r\n\r\n"; 
    $message = "From: ".$email."\n\n"; 
    
    mail($to, $subject, $body, $headers . "\r\nBCC: myname@hotmail.com");
    
    {function send_mail($email)
    
    
    {function valid_email($address)
    {
    	// check an email address is possibly valid
    	if (ereg('^[a-zA-Z0-9 \._\-]+@([a-zA-z0-9\-]*\.)+[a-zA-Z]+$',$address))
    	{
    		return true;
    	}
    	return false;
    }
    
    //inititialise an error array
    $errors = array();
    
    //check the content submitted by the user
    if(!valid_textfield($firstname))
    {
    	$errors[] = 'Firstname must be filled in and contain text only.';
    }
    if(!valid_textfield($lastname))
    {
    	$errors[] = 'Surname must be filled in and contain text only.';
    }
    if(!is_numeric($phone)||(strlen($phone)<6))
    {
    	$errors[] = 'Phone number must be a number at least 6 digits long'; 
    }
    if(!valid_email($email))
    {
    	$errors[] = 'Email Address must be in the following format - name@yourdomain.com'; 
    }
    //call the function to send the email
    return send_email($to, $subject, $message, $headers);
    
    function send_email($to, $subject, $message, $headers)
    {
    	//remove any content type, mime type, 
    	$to = clean_data($to);
    	$subject = clean_data($subject);
    	$message = clean_data($message);
    	$headers = clean_data($headers);
    	
    	if(mail($to, $subject, $message, $headers))
    	{
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    }
    
    function clean_data($text)
    {
     	// Remove injected headers
       	$find = array("Content-Type:", "Mime-Type:", "Content-type:", "MIME-Type:");
       	$ret = str_replace($find, "**bogus header removed**", $text);
       	return $ret;
    }
    }
    }
    
    	?>
    and this is the relevant html piece:

    Code:
    <input type="text" name="name">
    <em> *</em>E-mail: <input type="text" name = "email"><br><br><br/>
    
    
    
    <input type="submit" value="Submit Test">
    
    <input type=reset value=Clear>
    </form>
    Thanks.

  13. #13
    SitePoint Wizard spence_noodle's Avatar
    Join Date
    Jan 2004
    Location
    uk, Leeds (area)
    Posts
    1,264
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Is the script all on one page? Even the html?

  14. #14
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    no I have a php page and a html page
    like this:
    Code:
    <form action="result.php" method="post" id="form_id">

  15. #15
    SitePoint Wizard spence_noodle's Avatar
    Join Date
    Jan 2004
    Location
    uk, Leeds (area)
    Posts
    1,264
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    I see.

    On the php page do you have:
    PHP Code:
    $email $_POST['email']; 
    You also need one for the "name" too.

  16. #16
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Maybe we should start small - we'll omit the filtering, security and validation for now.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title></title>
        </head>
        <body>
            <form action="submit.php" method="post">
                <input type="text" name="senderName" />
                <input type="text" name="senderEmail" />
                <textarea name="senderMessage"></textarea>
                <input type="submit" name="submit" value="submit" />
            </form>
        </body>
    </html>
    PHP Code:
    <?php
    $sSenderName 
    $_POST['senderName'];
    $sSenderEmail $_POST['senderEmail'];
    $sSenderMessage $_POST['senderMessage'];

    $aEmailMessage = array(
        
    'Name: ' $sSenderName,
        
    'Email: ' $sSenderName,
        
    'Message: ' $sSenderMessage,
    );

    $semailSubject 'You have a message!';

    if(
    mail('you@yourhost.com'$semailSubjectimplode("\r\n"$aEmailMessage)))
    {
        
    printf(
            
    'Thanks for your message %s',
            
    $sSenderName
        
    );
    }
    else
    {
        
    printf(
            
    'Sorry %s, your message failed.',
            
    $sSenderName
        
    );
    }
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  17. #17
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok I have implemented those changes in my php page, and I get the mail reply with the 3 fields filled in. I also inserted the test result line in the subject field, so I also get the result of the test sent to my email. That's progress! Thanks a lot!

    This is the php page
    Code:
    $sSenderName = $_POST['senderName'];
    $sSenderEmail = $_POST['senderEmail'];
    $sSenderMessage = $_POST['senderMessage'];
    
    $aEmailMessage = array(
        'Name: ' . $sSenderName,
        'Email: ' . $sSenderEmail,
        'Message: ' . $sSenderMessage,
    );
    
    $semailSubject = "Someone scored ". $score . " over ". $scoremax . "."; ;
    
    if(mail('myname@hotmail.com', $semailSubject, implode("\r\n", $aEmailMessage)))
    {
        printf(
            'Thanks for your message &#37;s',
            $sSenderName
        );
    }
    else
    {
        printf(
            'Sorry %s, your message failed.',
            $sSenderName
        );
    }
    ?>
    Now for the sanitising etc??

  18. #18
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have shortened the code a bit because I don't need a message text area or field:

    Code:
    // Mail things
    
    $sSenderName = $_POST['senderName'];
    $sSenderEmail = $_POST['senderEmail'];
    
    
    
    $aEmailMessage = array(
        'Name: ' . $sSenderName,
        'Email: ' . $sSenderEmail,
        
    );
    
    $semailSubject = "Someone scored ". $score . " over ". $scoremax . "."; ;
    
    if(mail('myname@hotmail.com', $semailSubject, implode("\r\n", $aEmailMessage)))
    
    
    ?>
    I assume the above code is still ok. At least it's working well, but how can I add the validation, anti-spam etc?
    Thanks

  19. #19
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can anyone suggest some validation, spam filtering etc for the above php code? Thanks

  20. #20
    SitePoint Wizard spence_noodle's Avatar
    Join Date
    Jan 2004
    Location
    uk, Leeds (area)
    Posts
    1,264
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Do you mean in the message field? If so you could make an array with words you don't want like sex or porn words, then use preg_match to look through the message field or whatever to find those words, and if preg_match does not then carry on with the script.

    PHP Code:
    $bad_words = array('word1''word2''word3''etc...');

    foreach(
    $bad_words as $word) {
         if (
    preg_match("/$word/i""$message$otherfields")) {
              echo 
    'A bad word has been found!';
         }else{
              echo 
    'No bad words have been found';     
         }

    You world place the array way before any of the script then place the foreach loop after the variables.

  21. #21
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the reply. I was wondering if it might be possible to use or adapt a code like this from php builder, to suit my existing php code?
    Code:
    <?php
    $to      = "bob@domain_example.co.za";
    $subject = $_REQUEST["subject"];
    $body = $_REQUEST["body"];
    $email = $_REQUEST["email"];
    
    $dodgy_strings = array(
                    "content-type:"
                    ,"mime-version:"
                    ,"multipart/mixed"
                    ,"bcc:"
    );
    
    function is_valid_email($email) {
      return preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si', $email);
    }
    
    function contains_bad_str($str_to_test) {
      $bad_strings = array(
                    "content-type:"
                    ,"mime-version:"
                    ,"multipart/mixed"
    		,"Content-Transfer-Encoding:"
                    ,"bcc:"
    		,"cc:"
    		,"to:"
      );
      
      foreach($bad_strings as $bad_string) {
        if(eregi($bad_string, strtolower($str_to_test))) {
          echo "$bad_string found. Suspected injection attempt - mail not being sent.";
          exit;
        }
      }
    }
    
    function contains_newlines($str_to_test) {
       if(preg_match("/(%0A|%0D|\\n+|\\r+)/i", $str_to_test) != 0) {
         echo "newline found in $str_to_test. Suspected injection attempt - mail not being sent.";
         exit;
       }
    } 
    
    if($_SERVER['REQUEST_METHOD'] != "POST"){
       echo("Unauthorized attempt to access page.");
       exit;
    }
    
    if (!is_valid_email($email)) {
      echo 'Invalid email submitted - mail not being sent.';
      exit;
    }
    
    contains_bad_str($email);
    contains_bad_str($subject);
    contains_bad_str(body);
    
    contains_newlines($email);
    contains_newlines($subject);
    
    $headers = "From: $email";
    mail($to, $subject, $body, $headers);
    echo "Thanks for submitting.";
    ?>
    The above code is supposed to be pretty secure. Any ideas how I could adapt it to suit my php code? Thanks

  22. #22
    SitePoint Wizard spence_noodle's Avatar
    Join Date
    Jan 2004
    Location
    uk, Leeds (area)
    Posts
    1,264
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Yea, you only need to change the following:

    From this:
    PHP Code:
    $to      "bob@domain_example.co.za";
    $subject $_REQUEST["subject"];
    $body $_REQUEST["body"];
    $email $_REQUEST["email"]; 
    To this:
    PHP Code:
    $score $_POST['score']; //add this and change post to match
    $scoremax $_POST['scoremax']; //add this and change post to match
    $to      "your@email.com";
    $subject "Someone scored";
    $body "The results: Scored "$score " over "$scoremax ".";
    $email $_POST['senderEmail'];
    $name $_POST['senderName']; //add this 
    Hope this helps, as you may have noticed you may have to change the score and scoremax POST's to match what your form has, etc...

  23. #23
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks. I have made those changes, but now when I press submit test, I get the message "invalid email address, mail not sent" but I used a valid myname.hotmail.com address.
    The code I changed is:
    Code:
    $score = $_POST['score']; //add this and change post to match
    $scoremax = $_POST['scoremax']; //add this and change post to match
    $to      = "myname@hhotmail.com";
    $subject = "Someone scored";
    $body = "The results: Scored ". $score . " over ". $scoremax . ".";
    $email = $_POST['email'];
    $name = $_POST['name']; //add this 
    
    
    $dodgy_strings = array(
                    "content-type:"
                    ,"mime-version:"
                    ,"multipart/mixed"
                    ,"bcc:"
    );
    
    function is_valid_email($email) {
      return preg_match('#^[a-z0-9.!\#$&#37;&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si', $email);
    }
    
    function contains_bad_str($str_to_test) {
      $bad_strings = array(
                    "content-type:"
                    ,"mime-version:"
                    ,"multipart/mixed"
    		,"Content-Transfer-Encoding:"
                    ,"bcc:"
    		,"cc:"
    		,"to:"
      );
      
      foreach($bad_strings as $bad_string) {
        if(eregi($bad_string, strtolower($str_to_test))) {
          echo "$bad_string found. Suspected injection attempt - mail not being sent.";
          exit;
        }
      }
    }
    
    function contains_newlines($str_to_test) {
       if(preg_match("/(%0A|%0D|\\n+|\\r+)/i", $str_to_test) != 0) {
         echo "newline found in $str_to_test. Suspected injection attempt - mail not being sent.";
         exit;
       }
    } 
    
    if($_SERVER['REQUEST_METHOD'] != "POST"){
       echo("Unauthorized attempt to access page.");
       exit;
    }
    
    if (!is_valid_email($email)) {
      echo 'Invalid email submitted - mail not being sent.';
      exit;
    }
    
    contains_bad_str($email);
    contains_bad_str($subject);
    contains_bad_str(body);
    
    contains_newlines($email);
    contains_newlines($subject);
    
    $headers = "From: $email";
    mail($to, $subject, $body, $headers);
    echo "Thanks for submitting.";
    
    ?>
    and in the html page:

    Code:
       Name  <input type="text" name="name" />
               Email <input type="text" name="email" />
               
                <input type="submit" name="submit" value="submit" />
    
    <input type=reset value=Clear>
    </form>


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
  •