Take the 2-minute tour ×
$clean = array();

$email_pattern = '/^[^@\s<&>]+@([-a-z0-9]+\.)+[a-z]{2,}$/i';

if (preg_match($email_pattern, $_POST['email'])) 
$clean['email'] = $_POST['email']; 

The example code above (Source) uses an array called $clean to store the filtered value from $_POST. It's considered a security good practice. What are the advantages of using such an approach?

share|improve this question
php.net/manual/en/… –  Florian Margaine Jan 19 '13 at 16:07
add comment

1 Answer

Using this approach compared to which one? Not validating the input? Validating the input but storing it back in $_POST?

  1. Not validating the input at all is harmful security-wise, since it means that you fully trust any user. Note that client-side validation doesn't count, since circumventing it is elementary.

    By the way, here, validation is incomplete and especially encourage DOS attacks. If a malicious person submits a very large value for the field, evaluating it with the regular expression will take a huge amount of time and resources, eventually resulting in a denial of service if the request is repeated enough times.

    In the particular case of the e-mail address, the validation is also incorrect. But it's up to you to decide whether you are ready to use the real, RFC822-compliant, regular expression instead or stick with an incorrect one.

  2. Storing values back to $_POST, i.e. doing something like:

    if (!AppController::ValidateEmail($_POST['email']))

    is less risky, since $_POST values wouldn't be reassigned by the user, but still has a drawback: you're using a variable which is in global scope. This means that if you are calling some code between the moment when you validate the inputs and when you use them, this intermediary code can modify the $_POST data and introduce unexpected values.

share|improve this answer
add comment

Your Answer


