PHP:使用正则表达式执行表单验证,然后提交

时间:2014-09-01 23:43:28

标签: php regex validation

以下脚本可以很好地验证输入。问题是在验证之后我想将数据发送到另一个脚本,以便它可以存储在数据库中。如何编辑动作属性以获得我想要的内容?

<!DOCTYPE HTML> 
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 

<?php
$nameErr = "";
$name = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   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"; 
     }
   }
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

<h2>PHP Form Validation Example :</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   Name: <input type="text" name="name" value="<?php echo $name;?>">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>

<?php
echo "<h2>Input:</h2>";
echo $name;
?>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

开始会话:

session_start();

将表单数据存储在会话中:

$_SESSION['form_data'] = $_POST;

重定向到新脚本:

header("Location: new_script.php");

在新脚本中,从会话中检索数据并将其插入数据库。有关详细信息,请参阅PDO