SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    NYC
    Posts
    80
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Need help with form to email/sendMail issues

    Hey Guys,

    I've been working on a contact form for an event microsite that needs to send all form data to an email address. Simple enough as there are plenty of scripts out there. The caveat is I wanted it to resemble something closer to .NET's postback where it posts to the same page as well as use my layout for error validation. I've gotten both the validation and the form pretty close and it generally works but there are a few things I'm having trouble figuring out:

    1) At present, the code just sends the message text, how do I modify to send all the fields to the email recipient and format them in html to something like:

    Name: John Doe (concatenating first and last name variables)
    Phone: 123-123-1233
    Email: username@domain.com
    Message: Lorem ipsum...

    Even barebones plain text would suffice:

    John Doe
    123-123-1234
    jane@doe.com

    I really love your site...etc.etc.

    Mostly concerned with how to generally format. Once the code is in place, I can play around with it to get it to do what I need.

    On another related note, Is there a way to supress the phone output if the field is left blank?

    2) How do I set this so all the email the person receives comes from a static address like noreply@myhost.com, or admin@myhost.com rather than using the $name and $email variables in line 57? And, if I did decide to keep it, how do I concatenate $first_name and $last_name in that line? Like this?

    Code:
    $from    = "From: $first_name . $last_name <$email>\r\nReply-To: $email\r\n";
    3) Currently, validation works but whenever I try to add a style class to the <div> with the error message, it suppresses the validation. For example, try to add the .error class to the div tag on line 21:

    Code:
    <div><?php echo $error1; ?></div>
    If you reload the blank form and try to submit, you'll see the error message won't show. Remove the class and it shows. How can I style this?

    Here's working a test page I created with basic styles. You'll just have to put your email in line 4 for testing.

    Code:
    <?php
    
    // Define your email address - where to send messages - here
    define("MAIL_TARGET","name@whatever.com");
    
    // Define error messages
    define("errorFirstName","Invalid name! It must be at least 2 characters long.");
    define("errorLastName","Invalid name! It must be at least 2 characters long.");
    define("errorPhone","Please enter your phone number. It must be at least 10 characters long.");
    define("errorEmail","Invalid email address!");
    define("errorMsg","Invalid message! It must be at least 10 characters long.");
    
    function createForm($first_name="",$last_name="",$phone="",$email="",$message="",$error1="",$error2="",$error3="",$error4="",$error5=""){
    ?>
    
    <h2>Contact</h2><br />
    <p>For more information on 2009 E-MUG, please contact...yaddda yadda. You may also submit your query in the form below and a representative will be in touch with you shortly.</p>
    
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            <p><label>*First Name:</label><input type="text" name="first_name" class="textbox" value="<?php echo $first_name; ?>"></p>
            <div><?php echo $error1; ?></div>
                   
            <p><label>*Last Name:</label><input type="text" name="last_name" class="textbox" value="<?php echo $last_name; ?>"></p>
            <div><?php echo $error2; ?></div>
            
            <p><label>Phone:</label><input type="text" name="phone" class="textbox" value="<?php echo $phone; ?>"></p>
            <div><?php echo $error3; ?></div>
            
            <p><label>*E-mail:</label><input type="text" name="email" class="textbox" value="<?php echo $email; ?>"></p>
            <div><?php echo $error4; ?></div>
            
            <p><label>Message:</label><textarea name="message" rows="10" cols="50" class="textbox-msg"><?php echo $message; ?></textarea><br /></p>
            <div><?php echo $error5; ?></div>
            
            <p><label><em>* Required Fields</em></label></p> 
            <p><input type="submit" name="submitBtn" value="Submit" class="submit"></p>
          </form>
    <?php
    }
    
    // This function validates an email address
    function isValidEmail($email){
       $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
         
       if (eregi($pattern, $email)){
          return true;
       }
       else {
          return false;
       }   
    }
    
    // This function sends an email to the given address
    function sendMail($first_name,$last_name,$phone,$email,$message,$subject){
        
        $subject = "2009 E-MUG Contact Data";
        $from    = "From: $first_name . $last_name <$email>\r\nReply-To: $email\r\n"; 
        $header  = "MIME-Version: 1.0\r\n"."Content-type: text/html; charset=iso-8859-1\r\n";
        $content = htmlspecialchars($message);
        
        $content = wordwrap($content,70);
        @mail(MAIL_TARGET,$subject,$content,$from.$header);
    
    }
    ?>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    
    <style type="text/css">
    <!--
    /* =Forms
    末末末末末末末末末末末末末末末末末末末末末末末末末末末末末末末末末*/	
    #main label {
    	font-size:11px;
    	display: block;
    	}
    #main .submit input {
    	margin-left: 0em;
    	}
    #main input {
    	font-family: Arial, Helvetica, sans-serif;
    	font-size: 13px;
    	color: #333;
    	background: #f1f1f1;
    	padding: 2px;
    	border: 1px solid #999;
    	width: 200px;
    	}
    #main .submit {
    	color: #000;
    	background: #ccc;
    	border: 2px outset #d7b9c9;
    	width: 100px;
    	}
    #main .error {
    	font-family: Arial, Helvetica, sans-serif;
    	font-size: 12px;
    	color: red;
    	display:none;
    }	
    .textbox {
    	font-family: Arial, Helvetica, sans-serif;
    	font-size: 13px;
    	color: #333;
    	background: #f1f1f1;
    	padding: 2px;
    	border: 1px solid #999;
    	width: 200px;
    	}
    .textbox-msg {
    	font-family: Arial, Helvetica, sans-serif;
    	font-size: 13px;
    	color: #333;
    	background: #f1f1f1;
    	padding: 2px;
    	border: 1px solid #999;
    	width: 400px;
    	}
    
    .button {
    	color: #000;
    	background: #ccc;
    	border: 2px outset #d7b9c9;
    	width: 100px;
    	}
    -->
    </style>
    </head>
    
    <body>
    
    
    <div id="wrap">
        <div id="main">
    
    <?php if (!isset($_POST['submitBtn']))  {
        createForm();
    } else  {
          $first_name = isset($_POST['first_name']) ? $_POST['first_name'] : "";
          $last_name    = isset($_POST['last_name'])    ? $_POST['last_name'] : "";
          $phone   = isset($_POST['phone'])   ? $_POST['phone'] : "";
    	  $email   = isset($_POST['email'])   ? $_POST['email'] : "";
          $message = isset($_POST['message']) ? $_POST['message'] : "";
    
          $error  = false;
          $error1 = '';
          $error2 = '';
          $error3 = '';
    	  $error4 = '';
    	  $error5 = '';
    
          if (strlen($first_name)<2) {
              $error = true;
              $error1 = errorFirstName;
          }
    	  if (strlen($last_name)<2) {
              $error = true;
              $error2 = errorLastName;
          }
    	  if (strlen($phone)<10) {
              $error = true;
              $error3 = errorPhone;
          }
          if (!isValidEmail($email)) {
              $error = true;
              $error4 = errorEmail;
          }
          if (strlen($message)<10) {
              $error = true;
              $error5 = errorMsg;
          }
    
          if ($error){
             createForm($first_name,$last_name,$phone,$email,$message,$error1,$error2,$error3,$error4,$error5);
          }
          else {
              sendMail($first_name,$last_name,$phone,$email,$message,$subject);
        ?>
    
    <h2>Thank You!</h2><br />
    <p>Thank you for your interest. A representative will be in touch with you shortly.</p>
    <?php
        }
    }
    ?>
    
    	</div>
    </body>
    </html>
    Any and all help is appreciated.

    Thx,
    Pete

  2. #2
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    NYC
    Posts
    80
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Looks like most of my issues are solved:

    Error CSS is working thanks to the guys on my other thread (Thanks again!) Got the $from concatenation sorted out by creating a new variable called $full_name that concatenates $first_name and $last_name, then just used the $full_name variable in the $from line. Not sure if it's the most elegant way of doing it but it works.

    Code:
    function sendMail($first_name,$last_name,$phone,$email,$message,$subject){
        $full_name = $first_name . ' ' . $last_name;
        $subject = "2009 Contact Data";
        $from    = "From: $full_name <$email>\r\nReply-To: $email\r\n"; 
        $header  = "MIME-Version: 1.0\r\n"."Content-type: text/html; charset=iso-8859-1\r\n";
        $content = htmlspecialchars($message);
        
        $content = wordwrap($content,70);
        @mail(MAIL_TARGET,$subject,$content,$from.$header);
    
    }
    Now if I can just get the sendMail function to mail all the fields rather than just the subject, all will be golden.

  3. #3
    messing with my mind fristi's Avatar
    Join Date
    Feb 2009
    Posts
    292
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by NitroLiq View Post
    Now if I can just get the sendMail function to mail all the fields rather than just the subject, all will be golden.

    You only get the $message in the body of the email because that is the only thing you are putting in the body. I don't know anything about html formatting in the email, I never had to use it so far. So I can not help you with that. But try this function without the formatting:

    PHP Code:

    function sendMail($first_name,$last_name,$phone,$email,$message,$subject){
        
    $full_name $first_name ' ' $last_name;
        
    $subject "2009 Contact Data";
        
    $from    "From: $full_name <$email>\r\nReply-To: $email\r\n"
        
    $header  "MIME-Version: 1.0\r\n"."Content-type: text/html; charset=iso-8859-1\r\n";
        
    $content 'hello ' $full_name '\n';
        
    $content .= $phone '\n' $email '\n';
        
    $content .= $message;
        
    $content htmlspecialchars($content);
        
    $content wordwrap($content,70);
        @
    mail(MAIL_TARGET,$subject,$content,$from.$header);


    To PHP or to Perl, that is the question!
    (Bucket - simpletest) User

  4. #4
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    NYC
    Posts
    80
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yep, I figured it out a little later. This was the solution I came up with (You can tell me if it's good or bad...it works, in any case):

    PHP Code:
    function sendMail($first_name,$last_name,$phone,$email,$message,$subject){
        
    $full_name $first_name ' ' $last_name;
        
    $subject = ("2009 Contact Data");
        
    $from    "From: $full_name <$email>\r\nReply-To: $email\r\n"
        
    $header  "MIME-Version: 1.0\r\n"."Content-type: text/html; charset=iso-8859-1\r\n";
        
    $content '<strong>Name:</strong>' ' ' .  $full_name.'<br />'.
                   
    '<strong>Phone:</strong>' ' ' .  $phone.'<br />'.
                   
    '<strong>E-mail:</strong>' ' ' .  $email.'<br /><br />'.htmlspecialchars($message); 
                                  
        
    $content wordwrap($content,70);
        @
    mail(MAIL_TARGET,$subject,$content,$from.$header); 
    I really need to do some researching on best practices with PHP since I'm starting from scratch...I'm more of a front-end designer/coder and the little bit of back-end work I've done has been primarily with .NET and C# with our corporate site. We just migrated it into Drupal so now I'm in the fun position of learning both PHP and Drupal so I can actually do some back-end work with it.

  5. #5
    messing with my mind fristi's Avatar
    Join Date
    Feb 2009
    Posts
    292
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't see any problems with your solution

    For best practices I would say to first practice the basic PHP programming untill you know most things there is to know. Then grow into seperating your HTML (view) and your PHP code. Then move onwards to design Patterns and OOP ect... (looking at your programming history)
    First walk, then run
    To PHP or to Perl, that is the question!
    (Bucket - simpletest) User

  6. #6
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    NYC
    Posts
    80
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah, I mean right now, it's the syntax that's throwing me off (when to use single quotes, double, slashes, periods, etc.) I just want to keep best practices, security, and all that in mind from the onset rather than develop bad practices from the start. That's sort of the caveat when beginning at point A—you may be able to get things to work but you don't know if you're going about things the long way or maybe you're writing messy, badly organized code open to attacks. I'm probably going to pick up the O'Reilly books for php and drupal and look into separating code from view right off the bat (present contact form excluded).

  7. #7
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Location
    NYC
    Posts
    80
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually, going with what I just wrote, what's the best way to style what's in the $content variable if I wanted all the text to be output as Arial, Helvetica, sans-serif; 10px? Can I reference my stylesheet in some way or do I have to go in to each string and variable and somehow wrap each within <font></font> tags? This doesn't seem appropriate from a semantic point of view.


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
  •