PHP表单验证和处理同一页面

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP表单验证和处理同一页面相关的知识,希望对你有一定的参考价值。

great to validate and process a form in the same page
  1. <?php
  2.  
  3. function VerifyForm(&$values, &$errors)
  4. {
  5. // Do all necessary form verification
  6.  
  7. if (strlen($values['name']) < 3)
  8. $errors['name'] = 'Name too short';
  9. elseif (strlen($values['name']) > 50)
  10. $errors['name'] = 'Name too long';
  11.  
  12. // Needs better checking ;)
  13. if (!ereg('.*@.*..{2,4}', $values['email']))
  14. $errors['email'] = 'Email address invalid';
  15.  
  16. if (strlen($values['text']) == 0)
  17. $errors['text'] = 'Text required';
  18.  
  19. return (count($errors) == 0);
  20. }
  21.  
  22. function DisplayForm($values, $errors)
  23. {
  24. ?>
  25. <html>
  26. <head>
  27. <title>Yadda yadda</title>
  28. <style>
  29. TD.error
  30. {
  31. color: red;
  32. font-weight: bold;
  33. }
  34. </style>
  35. </head>
  36. <body>
  37.  
  38. <?php
  39. if (count($errors) > 0)
  40. echo "<p>There were some errors in your submitted form, please correct them and try again.</p>";
  41. ?>
  42.  
  43. <form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
  44. <table>
  45. <tr>
  46. <td>Name:</td>
  47. <td><input type="text" size="30" name="name" value="<?= htmlentities($values['name']) ?>"/>
  48. <td class="error"><?= $errors['name'] ?></td>
  49. </tr>
  50. <tr>
  51. <td>Email:</td>
  52. <td><input type="text" size="30" name="email" value="<?= htmlentities($values['email']) ?>"/>
  53. <td class="error"><?= $errors['email'] ?></td>
  54. </tr>
  55. <tr>
  56. <td valign="top">Text:</td>
  57. <td>
  58. <textarea name="text" cols="30" rows="6"><?= htmlentities($values['text']) ?></textarea>
  59. </td>
  60. <td class="error"><?= $errors['text'] ?></td>
  61. </tr>
  62. <tr><td colspan="2" align="center"><input type="submit" value="Submit"></tr>
  63. </table>
  64. </form>
  65.  
  66. </body>
  67. </html>
  68. <?php
  69. }
  70.  
  71. function ProcessForm($values)
  72. {
  73. mail('[email protected]', 'Form test', $values['text'], "From: "{$values['name']}" <{$values['email']}>");
  74.  
  75. // Replace with actual page or redirect :P
  76. echo "<html><head><title>Thank you!</title></head><body>Thank you!</body></html>";
  77. }
  78.  
  79. if ($_SERVER['REQUEST_METHOD'] == 'POST')
  80. {
  81. $formValues = $_POST;
  82. $formErrors = array();
  83.  
  84. if (!VerifyForm($formValues, $formErrors))
  85. DisplayForm($formValues, $formErrors);
  86. else
  87. ProcessForm($formValues);
  88. }
  89. else
  90. DisplayForm(null, null);
  91. ?>

以上是关于PHP表单验证和处理同一页面的主要内容,如果未能解决你的问题,请参考以下文章

PHP PHP表单验证和处理相同的页面

php中的注册表单验证

PHP 表单验证

PHP + jQuery + Ajax 表单提交 - 同一页面返回结果

PHP 表单

PHP 表单 - 提交时停留在同一页面上