Skip to main content
Code Review

Return to Revisions

3 of 3
Commonmark migration

Validation before sending mail in PHP

In my initial problem posted on SO, whenever anyone accessed the Mail.php on the server, it used to send an empty email to the $to. To avoid this I came up with a solution.

require 'PHPMailer/PHPMailerAutoload.php';
 
 $yourName = $_POST['yourName'];
 $sender = $_POST['emailID'];
 $subject = $_POST['subject'];
 $message = $_POST['message'];
 $to = '[email protected]';
 if(empty($yourName) || empty($sender) || empty($subject) || empty($message) || empty($message))
 {
 echo "Fields are empty";
 }
 else
 {
 $mail = new PHPMailer;
 //$mail->SMTPDebug = 2; 
 $mail->isSMTP(); 
 $mail->Host = 'smtp.gmail.com'; 
 $mail->SMTPAuth = true; 
 $mail->Username = 'gmailUser'; 
 $mail->Password = 'gmailPassword'; 
 $mail->SMTPSecure = 'tls'; 
 $mail->Port = 587; 
 $mail->setFrom($sender,$yourName);
 $mail->addAddress($to); 
 $mail->addReplyTo($sender);
 $mail->isHTML(true); 
 $mail->Subject = $subject;
 $mail->Body = "<b>From: </b>". $sender. "<br>" ." <b>Name: </b>". $yourName. "<br>". "<b> Message Body </b>" .$message;
 $mail->AltBody = "<b>From: </b>". $sender. "<br>" ." <b>Name: </b>". $yourName. "<br>". "<b> Message Body </b>" .$message;
 if(!$mail->send()) 
 {
 echo 'Message could not be sent.';
 echo 'Mailer Error: ' . $mail->ErrorInfo;
 } 
 else 
 {
 echo "Message has been sent....You're being redirected.....";
 }
 }

This fix, basically allows the user to interact with Mail.php, but Mail.php doesn't sends a null email to $to

Now hours later, I find out that this is a very bad approach.

I would like to know how a professional would solve this problem?

Any good approach which I could use to efficiently optimize the code?

Yash
  • 167
  • 9
lang-php

AltStyle によって変換されたページ (->オリジナル) /