我有一个联系表单,所有的php都可以正常发送电子邮件,但问题是一旦页面加载/刷新就会发送一封电子邮件。我希望代码只在填写了一个表单(带有多个输入)并且输入了提交按钮时执行。
<form>
Full Name:<input required type="text" name="fullname" action="currentFile.php"/>
<input type="submit"/>
</form>
<?php
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'mail@gmail.com';
$mail->Password = 'pass';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->addAddress('mail@gmail.com');
$mail->Subject = 'Contact Form';
$mail->Body = "Test";
$mail->AltBody = "Test";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>
如果有人能解释如何制作它,那么上面的php只在表单填写并点击按钮时执行才会感激。谢谢。
答案 0 :(得分:2)
Before posting here I attempted to wrap my execution code in an if(isset($_POST['fullname']))
statement, but this didn't work so I cam here seeking assistance. Thanks to those commenting on my post, I realised what the issue was; I didn't specify the method of data transfer in my form tag. Furthermore, mentioned the action attribute in the input tag as opposed to the form tag, which is incorrect.
The html should instead look like this:
<form action="currentFile.php" method="post">
Full Name:<input required type="text" name="fullname"/>
<input type="submit"/>
</form>
The issue I had was simply a result of poor HTML.