0

It's possible avoid totally SQL injection allowing ONLY A-Z/0-9 in GET or POST parameter?

if(preg_match("/^[a-zA-Z0-9]+$/", $_GET['myVal']) == 1) {
    $myValue = $_GET['myVal'];
} else {
    die();
}

It's a good practice? It's possible defeat this way? Thanks

John Wiky
  • 19
  • 5
  • 2
    just use mysql(i)_escape_string functions – Iłya Bursov Apr 14 '18 at 04:02
  • Yes, I know that it's possible. But I'm just curious trying find new ways. – John Wiky Apr 14 '18 at 04:04
  • Usually DB drivers includes SQL sanitization functions that are safe and optimized for performance. Check their documentation and save your time. – profimedica Apr 14 '18 at 04:33
  • Yes, it's possible as SQL injection requires the use of special characters other than a-zA-Z0-9. No, it's not good practice. What if you need to allow special characters into your values? Do you keep modifying the preg_match to allow them? Best practice is to use prepared statements. This [answer](https://stackoverflow.com/questions/8263371/how-can-prepared-statements-protect-from-sql-injection-attacks) explains it well. – Nick Apr 14 '18 at 05:09
  • How it's possible if special characters is not allowed with this rule? – John Wiky Apr 14 '18 at 05:12
  • @JohnWiky why risk it when you're safe if you're using prepared/parameterized queries? Making rules like this will eventually fail, either because someone finds some sneaky hack for it (charset, escaping etc) or because you lift some of the rules because fieldX needs to insert a wider character set. Ie many europeans would not be able to save their name or address in a system where all fields have insert rules as you outline above – JimL Apr 14 '18 at 05:33
  • @JohnWiky sorry about the confusion I meant it is possible to **avoid** SQL injection with your method because SQL injection requires special characters. – Nick Apr 14 '18 at 05:36
  • Thanks for this explanation guys!! – John Wiky Apr 14 '18 at 05:44
  • No. Those pesky injectors can find ways around your validator. By all means, set user friendly limits on user input, but not to the extent of forgoing the use of proper prepared and bound statements. – Strawberry Apr 14 '18 at 06:51

0 Answers0