Search code examples
phpmysqlsql-injectionphp4

How to prevent SQL injection of $_POST e-mail field using PHP 4


This would be a bit easier if I was able to use PHP 5 unfortunately this is not a viable option?

I am already using RFC 2822 from this stackoverflow thread to validate the e-mail format is valid, granted this is using JS on the form page which is not the best practice.

I will again verify it conforms to this format before saving it but I was wondering if there were any methods that should be used to help prevent SQL injection?


Solution

  • Wrong way - "Never trust user input"!

    First be sure the data is in the format you want, then query database. So first, check if $_POST[email_address] is in a valid email format, e.g. with regex. Only if it is in a valid email format, you query the database.

    Code for email regex (PHP):

    <?php
    $email = "test@test.com";
    
    if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
      echo "Email is valid.";
    }
    else {
    
      echo "Email in invalid.";
    }
    ?>