PHPMailer required fields

Discussion in 'PHP' started by timofthee, Feb 12, 2010.

  1. #1
    Hello all,

    I am very new to PHP and have a question about making fields in my html form required using a PHPMailer script. The current script that I am using that works is:

    <?php
    error_reporting(E_ALL);
    include_once('class.phpmailer.php');

    $mail = new PHPMailer();
    $mail->IsSMTP();
    //$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
    $mail->SMTPAuth = true; // enable SMTP authentication
    $mail->Host = "bluestar4.ukhost4u.com"; // sets the SMTP server
    $mail->Port = 25; // set the SMTP port for the GMAIL server
    $mail->Username = "test@email.com"; // SMTP account username
    $mail->Password = "monkey"; // SMTP account password

    $mail->From = "test@email.com";
    $mail->FromName = "UK Website";
    $mail->Subject = "UK Contact Form Submission";

    $mail->AddAddress("tim@email.com", "Tim");

    $message = "Message from UK Contact Form<br><hr>";

    foreach ($_POST as $key => $value) {
    $message .= "<br>".$key.": ".$value;
    }
    $mail->MsgHTML($message);

    if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
    header("Status: 200");
    header("Location: /thankyou-contact.htm");
    }
    ?>


    Can anyone assist me with how I would make some fields required on my website form?

    Thanks a million in advance!
     
    timofthee, Feb 12, 2010 IP
  2. systematical

    systematical Peon

    Messages:
    81
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Here is an easy way to do this.

    Lets say you have an email, name, and phone field.

    
    $requiredArr = array('email','name','phone');
    
    		foreach($_POST as $key => $value){
    			if(in_array($key,$requiredArr) && empty($value)){
    				$errorArr[] = 'Missing value for '.$key;
    			}
    		}
    		
    		if(count($errorArr) > 0){
    			// error stuff
    		}
    		else{
    			// send an email
    		}
    
    Code (markup):
     
    systematical, Feb 12, 2010 IP
  3. timofthee

    timofthee Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Do I just add this to the end of my code? What do I put for //error stuff and //send as email?
     
    timofthee, Feb 15, 2010 IP
  4. smb

    smb Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yes.

    For the //error stuff you can print the error message to the screen:
    echo "Missing a required value"; // or do a for loop and print every missing element in the $errorArr
    // or print the error as a comment for your own debuggin: echo("<!-- $errorArr --->");

    For the //send email:

    just include the logic you already have
     
    smb, Feb 15, 2010 IP