[英]PHP script not validating input
為什么此腳本不驗證電子郵件地址、姓名和電話號碼? 它正在發送電子郵件,但沒有通知我輸入字段中的故意錯誤。 (這個腳本是從 html 表單標簽調用的)。
<?php
// define variables and set to empty values
$emailErr = $nameErr = $phoneErr = "";
$email = $name = $phone = $message = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if phone number is valid (this regular expression also allows dashes in the phone number)
if (!preg_match("/^[0-9+'('+')'+ '-' ]*$/",$phone)) {
$phoneErr = "Invalid Phone Number";
}
}
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$message = $_REQUEST['message'] ;
mail( "omitted@omitted.com", "Contact Us Inquiry",
$message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}
?>
更新 6/23/15 幾乎午夜 EDT 表單現在驗證輸入,但我希望它更漂亮。
發布 HTML 表單標記和腳本標記的內容,向您表明我希望電子郵件、姓名和電話號碼錯誤出現在這些字段的輸入框的右側,如果有錯誤,我想留在 Contact_Us 頁面上。 我怎么做? (還在 HTML 表單內容下方發布工作 php 腳本。)
在 Head 標簽中:
<style>
.error {color: #00a261;}
</style>
在正文標簽中:
<p><span class="error">* required field. </span></p>
<form method="post" name="contact_us_form" action="contact_us_e_mail.php">
<div align="center">
Email: <input name="email" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php
echo $emailErr; ?>
</span><br /><br />
Name: <input name="name" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php echo $nameErr; ?>
</span><br /><br />
Phone: <input name="phone" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php echo $phoneErr; ?>
</span><br /><br />
Message:<br />
<textarea name="message" border-style: solid style="border-color:#00a261" rows="15" cols="80">
</textarea>
<br />
<input type="submit" value="Submit"/>
</form>
修改后的 php 腳本(稱為 contact_us_e_mail.php):
<?php
// define variables and set to empty values
$emailErr = $nameErr = $phoneErr = "";
$email = $name = $phone = $message = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format. Please use browser's back button and correct.";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed in Name. Please use browser's back button and correct.";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if phone number is valid (this regular expression also allows dashes in the phone number)
if (!preg_match("/^[0-9+'('+')'+'-']*$/",$phone)) {
$phoneErr = "Invalid Phone Number. Please use browser's back button and correct.";
}
}
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$message = $_REQUEST['message'] ;
if($nameErr == '' && $phoneErr == '' && $emailErr == ''){
mail( "omitted@omitted.com", "Contact Us Inquiry",
$message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}else{
echo $emailErr, "<br />";
echo $nameErr, "<br />";
echo $phoneErr, "<br />";
//$errorList = $nameErr . ' ' . $phoneErr . ' ' . $emailErr;
//header( "Location: http://omitted.com/Contact_Us.html" );
}
}
?>
好吧,您正在設置變量$nameErr, $phoneErr, $emailErr
但您從未測試過它們。
你應該像這樣用 if 包裹你的郵件聲明:
if($nameErr == '' && $phoneErr == '' && $emailErr == ''){
mail( "omitted@omitted.com", "Contact Us Inquiry", $message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}else{
$errorList = $nameErr . ' ' . $phoneErr . ' ' . $emailErr;
header( "Location: http://omitted.com/errors.php?errorList=" . $errorList );
}
這是破解那個特定堅果的一種方法。 關鍵是在決定向用戶呈現什么之前,在腳本的開頭檢查表單變量是否存在。 另一種選擇是使用FormData
對象和 AJAX 提交表單。 如果需要,您可以返回一個 JSON 對象,然后在客戶端使用 JS 決定是否隱藏/顯示錯誤消息並在成功時重定向到另一個頁面。
die
工作方式是這種方法的重要關鍵之一。 正如評論中提到的,它會停止對文件的任何進一步處理 - 無論是簡單地發出 html 還是正在評估 php 代碼。
如果“驗證”(我沒有執行)失敗,您會在有問題的字段旁邊看到一個星號。 它還會將可接受的字段重新放入表單中的輸入中,從而避免為了僅在其中一個輸入中出現錯誤而再次鍵入所有信息的需要。
只需將其扔到服務器上就可以玩了。 我對這種方法有兩種看法。 一方面,它將所有東西都連接在一個位置。 另一方面,您最終可能會在一個文件(php、html、css、js)中使用 4 種語言,並且某些東西很快就會變得有點糟糕,難以維護。
測試文件
<?php
/*
sample that contains a form that will sumbit to itself
*/
// nothing entered in the POST array - this means the page has been loaded as a result of a request originating
// somewhere _other_ than the form in this page.
// we'll need to display the page ready for a 'first-visit'
if (count($_POST) == 0)
{
//echo ('$_POST array is empty!<br>');
$username = $email = $message = '';
}
// no validation here, I'm assuming all are okay. You need to validate for yourself in this block of code.
// you'll notice that submitting an empty form gives us 3 vars in the POST array, all of which are empty strings
else
{
$username = $email = $message = '';
if (isset($_POST['username']) == true)
$username = $_POST['username'];
if (isset($_POST['email']) == true)
$email = $_POST['email'];
if (isset($_POST['message']) == true)
$message = $_POST['message'];
// use this block or the 7 lines above - they have the same effect.
/*
$username = isset($_POST['username']) == true ? $_POST['username'] : "";
$email = isset($_POST['email']) == true ? $_POST['email'] : "";
$message = isset($_POST['message']) == true ? $_POST['message'] : "";
*/
if ( strlen($username) == 0)
$usernameNotPresent = true;
if ( strlen($email) == 0)
$emailNotPresent = true;
if ( strlen($message) == 0)
$messageNotPresent = true;
if (( isset($usernameNotPresent)==false) && (isset($emailNotPresent)==false) && (isset($messageNotPresent) == false))
{
doSendMail();
// execution/parsing of the file will stop here. This has 2 effects.
// 1. Any further php code wont be interpreted and then run
// 2. Any html that follows a call to die wont be shown.
// Therefore, if we get here that means we've sent the email and there's no use in showing the
// email form.
// provided nothing has been output yet, you could also re-direct to another page with a call
// to the function header
die;
}
}
function doSendMail()
{
// ToDo:
// send the email here
// print a message telling the user of the outcome of trying to send the email.
echo "<p>Email successfully sent, please check your inbox</p>";
}
?>
<!doctype html>
<html>
<head>
<script>
</script>
<style>
.wrapper
{
display: inline-block;
}
#myForm
{
text-align: center;
}
#myForm > input, #myForm > textarea
{
/* display: block; */
margin-bottom: 16px;
width: 170px;
text-align: left;
}
#myForm > input[type='submit']
{
width: 50%;
text-align: center;
}
</style>
</head>
<body>
<div class='wrapper'>
<form id='myForm' method='post' action='' > <!-- an empty action attribute submits the form back to itself -->
<?php
if (isset($usernameNotPresent))
echo "<input type='text' name='username' placeholder='enter username'><span class='error'>*</span></br>";
else
echo "<input type='text' name='username' placeholder='enter username' value='$username'></br>";
?>
<?php
if (isset($emailNotPresent))
echo "<input type='text' name='email' placeholder='enter email address'><span class='error'>*</span></br>";
else
echo "<input type='text' name='email' placeholder='enter email address' value='$email'></br>";
?>
<?php
if (isset($messageNotPresent))
echo "<textarea name='message' placeholder='enter your message'></textarea><span class='error'>*</span></br>";
else
echo "<textarea name='message' placeholder='enter your message'>$message</textarea></br>";
?>
<div><input type='submit' value='GO'/></div>
</form>
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.