Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

php - phpmailer how to check if field is empty sintax

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("[email protected]", " First receipient");
$mail->AddCC("[email protected]", "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);
}
?> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...