php - 同一页面处理

标签 php process verification onsubmit

如何在同一页面上处理表单与使用单独的处理页面。现在,对于注册、评论提交等,我使用第二个页面来验证数据,然后提交并路由回 home.php。我怎样才能做到在提交时页面本身进行验证而不是使用第二页。

最佳答案

您可以告诉表单提交给 PHP 自身,然后检查表单处理的 $_POST 变量。这种方法非常适合错误检查,因为您可以设置一个错误,然后让表单重新加载用户之前提交的任何信息仍然完好无损(即他们不会丢失他们提交的内容)。

当点击“提交”按钮时,它会将信息发布到同一页面,在顶部运行 PHP 代码。如果发生错误(基于您的检查),表单将为用户重新加载,并显示错误,并且用户提供的任何信息仍在字段中。如果没有发生错误,您将显示一个确认页面而不是表单。

<?php
//Form submitted
if(isset($_POST['submit'])) {
  //Error checking
  if(!$_POST['yourname']) {
    $error['yourname'] = "<p>Please supply your name.</p>\n";
  }
  if(!$_POST['address']) {
    $error['address'] = "<p>Please supply your address.</p>\n";
  }

  //No errors, process
  if(!is_array($error)) {
    //Process your form

    //Display confirmation page
    echo "<p>Thank you for your submission.</p>\n";

    //Require or include any page footer you might have
    //here as well so the style of your page isn't broken.
    //Then exit the script.
    exit;
  }
}
?>

<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
  <?=$error['yourname']?>
  <p><label for="yourname">Your Name:</label><input type="text" id="yourname" name="yourname" value="<?=($_POST['yourname'] ? htmlentities($_POST['yourname']) : '')?>" /></p>
  <?=$error['address']?>
  <p><label for="address">Your Address:</label><input type="text" id="address" name="address" value="<?=($_POST['address'] ? htmlentities($_POST['address']) : '')?>" /></p>
  <p><input type="submit" name="submit" value="Submit" /></p>
</form>

关于php - 同一页面处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4783381/

相关文章:

php - strip <br>(n12br) 从数据库字段获取

swift - 在 Swift 中创建带参数的进程?

java - 尝试验证数字签名时出现异常

php - 存储注册时输入的数据

php - Laravel 在不使用 foreach 循环的情况下发送单独的多封邮件

PHP:如何遍历目录中的每个 XML 文件?

php - 使用 PHP POST 接收表单输入数据

c - 兄弟子进程之间的管道份额

java - 如何编写java程序获取pid

email - 通过电子邮件验证帐户 - 优点和缺点