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