/ Published in: PHP
great to validate and process a form in the same page
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php function VerifyForm(&$values, &$errors) { // Do all necessary form verification $errors['name'] = 'Name too short'; $errors['name'] = 'Name too long'; // Needs better checking ;) $errors['email'] = 'Email address invalid'; $errors['text'] = 'Text required'; } function DisplayForm($values, $errors) { ?> <html> <head> <title>Yadda yadda</title> <style> TD.error { color: red; font-weight: bold; } </style> </head> <body> <?php echo "<p>There were some errors in your submitted form, please correct them and try again.</p>"; ?> <form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST"> <table> <tr> <td>Name:</td> <td class="error"><?= $errors['name'] ?></td> </tr> <tr> <td>Email:</td> <td class="error"><?= $errors['email'] ?></td> </tr> <tr> <td valign="top">Text:</td> <td> </td> <td class="error"><?= $errors['text'] ?></td> </tr> <tr><td colspan="2" align="center"><input type="submit" value="Submit"></tr> </table> </form> </body> </html> <?php } function ProcessForm($values) { mail('[email protected]', 'Form test', $values['text'], "From: \"{$values['name']}\" <{$values['email']}>"); // Replace with actual page or redirect :P echo "<html><head><title>Thank you!</title></head><body>Thank you!</body></html>"; } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $formValues = $_POST; if (!VerifyForm($formValues, $formErrors)) DisplayForm($formValues, $formErrors); else ProcessForm($formValues); } else DisplayForm(null, null); ?>
URL: http://support.jodohost.com/showthread.php?t=4350