2

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?

Community
  • 1
  • 1
Eric
  • 565
  • 1
  • 8
  • 25
  • 1
    "not best practise" == "entirely useless against a deliberate attack" – Quentin Feb 14 '12 at 16:15
  • Not sure what you mean - protecting against SQL injection is the same in PHP 4 as it is in PHP 5. Do you mean E-Mail *header* injection? – Pekka Feb 14 '12 at 16:15
  • 1
    possible duplicate of [Best way to stop SQL Injection in PHP](http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php) – Quentin Feb 14 '12 at 16:15
  • 10
    **STOP. NOW.** If your host doesn't allow you access to PHP 5 you need to **DROP EVERYTHING** and switch hosts immediately. –  Feb 14 '12 at 16:16

2 Answers2

3

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.";
}
?>
citizenen
  • 703
  • 6
  • 24
djot
  • 2,952
  • 4
  • 19
  • 28
  • Ok, read just by now, that you checked for valid format. So how do you expect the data not to be EMAIL then? – djot Feb 14 '12 at 16:24
  • 1
    Of course, it's a good idea to validate the format, but for anything coming from the user, I would always recommend either prepared statements (which obviously isn't available in PHP 4, hence why rdlowrey's comment got so many upvotes), or at the very least escape it using `mysql_real_escape_string()` **in addition** to any sort of regex checks you might be using. – Mike Feb 14 '12 at 16:28
-1

use mysql_real_escape_string() on the input after you've validated its an email you should really be using that function on all your inputs that are going into the database.

Clark T.
  • 1,470
  • 2
  • 11
  • 25