我有一個表單,我試圖驗證電子郵件地址。如果電子郵件地址不正確,我想要輸入「請輸入有效的電子郵件地址」。返回到表單上的「電子郵件」輸入框中。我究竟做錯了什麼?沒有驗證正在發生。我收到我的電子郵件中的表格信息,一旦提交,用戶將被髮送到「謝謝」頁面,但沒有驗證。我可以在「電子郵件」輸入中添加任何內容,表單將提交。使用PHP的電子郵件驗證
<form action="../php/contact.php" method="post">
<p>First Name:</p>
<input class="box_style" type="text" name="first_name" required maxlength="20" />
<p>Last Name:</p>
<input class="box_style" type="text" name="last_name" required maxlength="25" />
<p>Email:</p>
<input class="box_style" type="text" name="email" required maxlength="50" />
<p>Contact Number (optional):</p>
<input class="box_style" type="text" name="contact_number" maxlength="12" />
<p>How did you find us?</p>
<select class="box_style" name="how" required>
<option value="choose">Select...</option>
<option value="referal">Referal</option>
<option value="website">Website</option>
<option value="search">Search Engine</option>
<option value="card">Business Card</option>
</select>
<p>Enquiries:</p>
<textarea class="box_style" name="inquiries" cols="30" rows="10"></textarea>
<input class="box_style" type="submit" name="submit" value="Submit"/>
</form>
,這是PHP
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$fName = $lName = $email = $cNum = $how = $enquiries = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = test_input($_POST["first_name"]);
$lName = test_input($_POST["last_name"]);
$cNum = test_input($_POST["contact_number"]);
$how = test_input($_POST["how"]);
$enquiries = test_input($_POST["enquiries"]);
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
}};
$email_from = '[email protected]';
$email_subject = "New Inquiry";
$email_body = "You have received a new message from" ." ". "$fName" ." ". "$lName" ."\n".
"$inquiries"."\n".
"Referal Type:" ." ". "$how" ."\n".
"Contact Number:" ." ". "$cNum" ."\n";
$to = "[email protected]";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
mail($to,$email_subject,$email_body,$headers);
?>
謝謝
看起來像驗證發生,但你沒有辦法處理它是對還是錯 – Ice76
'print「
請輸入一個有效的電子郵件地址
」; header(「Location:www.mysite/thankyou.com」);'你輸出一個響應,然後立即加載另一個頁面。所以這個反應就失去了。 – Martin是@Martin是對的。爲簡單表單處理腳本執行此操作的最佳方法是將所有邏輯移動到發佈到自身的一個腳本中。您將邏輯分成幾部分,您可以檢查請求是否位於頂部的帖子,並在其中設置錯誤。然後它轉到一切都好的部分(然後您發送電子郵件)或不是,並且您再次輸出表單,通常填充值和錯誤添加到顯示。 – gview