phpmailer how to check if field is empty sintax

梦想与她 提交于 2020-01-17 17:48:16

问题


Unfortunately I could not find the answer in other questions even though some of them seems to be similar. I am new to phpmailer but I managed to succesfully send email succesfully through smtp by using below code. However, I wish to stop sending emails with empty fields but I can't find proper sintax to do it and I would appreciate advise as how to stop email being sent if fields are empty or how to make fields required . (I know how to make client side validation but server side is a problem). Please see below:

<?php
if(isset($_POST['submit'])) {  
$message=
'Name:  '.$_POST['name'].'<br />
Subject:    '.$_POST['subject'].'<br />
Email:  '.$_POST['email'].'<br />
Message:    '.$_POST['message'].'';
require "PHPMailer-master/class.phpmailer.php";    
$mail = new PHPMailer();      
require "smtp.php";   
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->Subject = "Message from www";  
$mail->MsgHTML($message); 
$mail->AddAddress("address1@domain.com", " First receipient");
$mail->AddCC("address2@domain.com", "Second receipient");
$result = $mail->Send();  
$message = $result ? '<div class="alert alert-success" role="alert"> Message    has been sent ! </div>': '<div class="alert alert-danger" role="alert"><strong>Error!</strong> !</div>';  
unset($mail);
}
?> 

回答1:


You just need to tack on some checks into your if statement. empty() is great for checking for empty, null, or 0 fields

if(isset($_POST['submit']) 
   && !empty($_POST['name'])  
   && !empty($_POST['subject'])  
   && !empty($_POST['email'])  
   && !empty($_POST['message'])) {

You can do some validation before your if statement to make sure the fields are filled and valid, and throw an error if they aren't.




回答2:


Follow what @anyber has suggested, I just wanted to follow up and let you know that based on your code, this looks like a contact us form.

You don't want to set the from to the email that's entered on the form, you should change that to your email address. Setting the from with someone else's email can lead to a lot of problems, if that user has DMARC or other authentication methods enabled, take a look at this resource: Common Contact US Problems



来源:https://stackoverflow.com/questions/37575691/phpmailer-how-to-check-if-field-is-empty-sintax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!