如何在PHP中的页面之间导航

时间:2013-10-30 06:45:18

标签: php html validation navigation

我需要验证给定页面中的输入,然后,如果存在任何错误,那么我应该显示带有错误消息的同一页面。如果输入正确,那么我应该显示下一页。我怎么做到这一点?

enter code here

<html>
<head></head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$valid= true;
if (empty($_POST["name"]))
  {$nameErr = "Name is required";}
else
  {$name = test_input($_POST["name"]); $valid=false;}

if (empty($_POST["email"]))
  {$emailErr = "Email is required";}
else
  {$email = test_input($_POST["email"]); $valid=false;}

if (empty($_POST["pwd"]))
  {$pwdErr = "Password is required";}
else
  {$pwd = test_input($_POST["pwd"]); $valid=false;}

if (empty($_POST["gender"]))
  {$genderErr = "Gender is required";}
else
 {$gender = test_input($_POST["gender"]); $valid=false;}

 }
if($valid){
header('Location: dbregister.php');
exit();
 }

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

 ?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name : <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Email: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Password: <input type="password" name="pwd">
<span class="error">* <?php echo $pwdErr;?></span>
<br><br>
Gender: <input type="radio" name="sex" value="Male"> <input type="radio" name="sex"           value="Female">
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Click here to Submit: <input type="submit" value="register">
</form>
</body>
</html>

我能够验证输入并显示错误消息,但无法发送另一页说明注册成功'dbregister.php'

Also I am getting undefined error for $valid in if($valid){
   header('Location: dbregister.php');
   exit();}

1 个答案:

答案 0 :(得分:0)

有许多表单中的错误处理教程,例如http://www.w3schools.com/php/php_form_validation.asp

示例文件(名为index.php):

<?
    if(!isset($_POST["name"])){
        echo "<div>ERROR IN NAME FIELD</div>";
    }
?>
<form action="index.php">
    <input type="text" id="name">
    <input type="submit" value="Submit">
</form>