为了正常工作,我需要设置表单以首先检查验证,然后在验证通过后发布数据。这很好,但我不确定如何将验证代码与表单操作中的后置代码相结合。示例如果操作是:action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
表单正确验证但不发送到任何地方!如果我将表单操作更改为action="contact-engine.php">
,则表单已发布但未经验证!考虑到这一点,我需要结合到动作和验证然后(一旦通过验证)contact-engine.php问题是我根本不知道该怎么做?我真的是php的学习者,这对我来说很复杂!任何帮助都非常感谢我从现在开始工作几天! (N.B.两个页面都是.php)完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Help!</title>
<style type="text/css">
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Name
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}}
//Email
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" id="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><span class="error">* required field.</span></p><br />
<div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Name:<br />
<input type="text" name="name" class="border" size="25" value="<?php if(isset($_POST['name'])) {echo $_POST['name']; } ?>">
<span class="error"><?php echo $nameErr;?></span>
</div>
<div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Email: (please double check enty)<br />
<input type="text" name="email" class="border" size="25" value="<?php if(isset($_POST['email'])) {echo $_POST['email']; } ?>"><span class="error">
<?php echo $emailErr;?></span>
</div>
<div>
<input type="submit" value="Send" id="submit">
</div>
</form>
</body>
</html>
And below is the contact-engine code:
<html>
<head>
<title>Contact Engine</title>
</head>
<body>
<br />Name:<?php echo htmlspecialchars($_POST['name']); ?><br />
<br />Email:<?php echo htmlspecialchars($_POST['email']); ?><br />
</body>
</html>
答案 0 :(得分:2)
你可以试试这个。这是一个简单的代码,您可以通过它来实现此目的:
//sample index.php file
<?php
include 'submitted.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="text" name="foo" />
<input type="submit" value="submit">
</form>
</body>
</html>
在这里,我使用post方法将表单提交到同一页面。但是,我已经包含了另一个文件include 'submitted.php'
。
以下是submitted.php
//sample submitted.php
<?php
if(isset($_POST['foo']))
{
if(strlen($_POST['foo']) < 5){
echo "String length too small";
}
else
{
echo $_POST['foo'];
}
}
?>
对于测试,它只是检查长度是否超过五。如果不是,则会在页面所在的同一页面上显示错误消息。
自己测试一下。