Edited based on Cups advice.
PHP Code:
<?php
$required = array('name', 'email', 'message');
$errors = array();
$data = array();
if (count($_POST) >= 1)
{
array_map('trim', $_POST);
foreach ($_POST as $key => $value)
{
if (in_array($key, $required))
if (empty($value)) $errors[$key] = 'required';
$data[$key] = clean($value);
}
if (!preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', $data['email']))
{
$errors['email'] = 'invalid';
}
}
function clean($str)
{
return mysql_real_escape_string($str);
}
?>
2
$errors[$key] = 'empty'
Could you do this instead?
$errors['empty'] = $key ;
In case you later have $errors['invalid'] ?
The final formatting of errors may differ from invalid attempts.
Writing the errors in the keys would overwrite on each iteration of the loop, so it would probably be best to use the $_POST keys in the $errors array aswell
Huh,
if count( $required ) is equal to 3, then if your count of POST vars is less than 3 then send them far, far away. (header to your home page)
This seems too specialized at the moment, i'm trying to create a generic form processing template to work from. Also why would you check if $required is equal to 3, there could be a textbox for website which isn't required and if someone enters that I'd be sending someone away for no reason.
Thanks for your advice, very helpful
Bookmarks