Posted By

fackz on 01/23/09


Tagged


Versions (?)

Who likes this?

26 people have marked this snippet as a favorite

xtheonex
tjombka
jeremyhcobb
bryandease
umang_nine
fackz
nb109
CommissarXiii
Hollow
vali29
CSB
Pixelpower
cindreta
Adam42
oktijum
colingardom
scottwf
atomicbutterfly
jameshernandez
mecha
ericserrat
bkgoh
metthyn
mmcachran
wirenaught
robfahy


Sanitize data to prevent SQL Injection Attacks


 / Published in: PHP
 

This is a simple function that sanitizes the data before sending it to MySQL. First it removes whitespaces from the beginning and ending of the string. If magicquotesgpc is enabled and the data has been already escaped we will apply stripslashes() to the data. This way the data won’t be escaped twice when mysqlrealescape_string() is called.

Example: $username = sanitize($POST['username']); $password = sanitize($POST['password']);

  1. 1. function sanitize($data)
  2. 2. {
  3. 3. // remove whitespaces (not a must though)
  4. 4. $data = trim($data);
  5. 5.
  6. 6. // apply stripslashes if magic_quotes_gpc is enabled
  7. 8. {
  8. 9. $data = stripslashes($data);
  9. 10. }
  10. 11.
  11. 12. // a mySQL connection is required before using this function
  12. 13. $data = mysql_real_escape_string($data);
  13. 14.
  14. 15. return $data;
  15. 16. }

Report this snippet  

You need to login to post a comment.