[英]How to display the message sent on the contact form in PHP
我創建了一個聯系表單,它確實有效,但現在我想在“發送”按鈕正下方提交表單后顯示“已發送消息”。
HTML文件
<form action="send_mail.php" id="footer-form" method="post" role="form">
<div class="form-group has-feedback">
<label class="sr-only" for="name2">Name</label>
<input class="form-control" id="name2" name="name2" placeholder="Name" required="" type="text" />
</div>
<div class="form-group has-feedback">
<label class="sr-only" for="email2">Email address</label>
<input class="form-control" id="email2" name="email2" placeholder="Enter email" required="" type="email" />
</div>
<div class="form-group has-feedback">
<label class="sr-only" for="message2">Message</label>
<textarea class="form-control" id="message2" name="message2" placeholder="Message" required="" rows="8"></textarea>
</div>
<div class="6u 12u$(small)">
<input id="copy" name="copy" type="checkbox" />
<label for="copy">Email me a copy of this message</label>
</div>
<input class="btn btn-default" type="submit" value="Send" />
</form>
PHP 代碼(不同的文件)
<?php
$name = $_POST['name2'];
$email = $_POST['email2'];
$message = $_POST['message2'];
$formcontent ="From: $name \nMessage: $message";
$recipient = "hello@domain.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
?>
正如 Funk 四十人所說:
使用 if/else 語句:
<?php
$name = $_POST['name2'];
$email = $_POST['email2'];
$message = $_POST['message2'];
$formcontent ="From: $name \nMessage: $message";
$recipient = "hello@domain.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if(mail($recipient, $subject, $formcontent, $mailheader)) {
die("Error!");
} else {
echo "Success!";
}
?>
if/else
文檔: http : //php.net/manual/en/control-structures.elseif.php
您可以簡單地將您的 php 重定向到您的 html,並在您的mail()函數之后使用類似 success=true 的參數
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header('Location: index.php?success=true');
將您的 .html 重命名為 .php
並在您的 html(現在是 php)下
<input class="btn btn-default" type="submit" value="Send" />
<?php
if ( isset($_GET['success']) && $_GET['success']==true )
echo "Message Sent";
?>
非常簡單,使用帶有if/else
的條件語句。
if( mail($recipient, $subject, $formcontent, $mailheader) ){
echo "Sent";
} else {
echo "Error, check your logs";
}
另外,如果您的整個代碼都在同一個文件中,您最好對所有輸入/POST 數組使用條件語句並檢查empty()
字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.