Form processing with input checking, simple captcha and error reporting


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. $js_back = 'javascript:history.go(-1)';
  3.  
  4. if (isset($_POST['send']))
  5. {
  6. if ($_POST['captcha'] != 'hello')
  7. die('<p class="error">Antispam failed. <a href="'.$js_back.'">Try again</p>');
  8.  
  9. $secured = array();
  10. $secured = array_map('htmlspecialchars', array_map('strip_tags', $_POST));
  11. extract($secured);
  12.  
  13. $inputs = array('cname' => 'Firstname, surname', 'cemail' => 'Email', 'msg' => 'Message');
  14. foreach ($inputs as $key => $value)
  15. {
  16. if (empty(${$key}))
  17. die('<p class="error">Input '.$value.' is required. <a href="'.$js_back.'">Try again</a></p>');
  18. }
  19.  
  20. // Code...
  21. }
  22.  
  23. ?>
  24. <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
  25. <table>
  26. <tbody>
  27. <tr>
  28. <td><label for="cname">Firstname, surname:</label></td>
  29. <td><input type="text" name="cname" id="cname" size="40" /></td>
  30. </tr>
  31. <tr>
  32. <td><label for="cemail">E-mail:</label></td>
  33. <td><input type="text" name="cemail" id="cemail" size="40" /></td>
  34. </tr>
  35. <tr>
  36. <td><label for="msg">Message:</label></td>
  37. <td><textarea name="msg" rows="8" cols="38" id="msg"></textarea></td>
  38. </tr>
  39. <tr>
  40. <td>Antispam:</td>
  41. <td><input type="text" name="captcha" /> write in "hello"</td>
  42. </tr>
  43. <tr>
  44. <td>&nbsp;</td>
  45. <td><input type="submit" name="send" value="Send" /></td>
  46. </tr>
  47. </tbody>
  48. </table>
  49. </form>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.