Posted By

pckujawa on 01/16/07


Tagged

php input security web programming


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

d4rk
vali29
willcodeforfood


User input validation and security / general security in PHP and programming in general


 / Published in: PHP
 

I got most of these tips out of a great book published by O'Reilly (my favorite web-design publisher): "Programming PHP, 2nd Ed." by Lerdorf, Tatroe, and McIntyre. Another good book is "Essential PHP Security," also published by O'Reilly.

  1. Regarding user input (e.g. web forms, but pretty much any possible user input):
  2.  
  3. Check the length of the input to verify that it is less than your max (always set some sort of maximum) and greater than zero.
  4.  
  5. In PHP with MySQL, use the function "mysql_real_escape_string" when interacting with the database (db).
  6.  
  7. Always clean your output (to prevent XSS, or Cross-Site Scripting):
  8. In PHP, you can use the functions "htmlentities" for textual output and "urlencode" for URI's.
  9.  
  10. Never accept user input for filenames! Write your own filename, perhaps based on pre-cleaned user input, but preferably just an alphanumeric name of your choice (which can be stored in the db for reference). And before you write the file, use the PHP functions "basename" and "realpath" (i.e. basename(realpath($filename)) ) in order to establish exactly where the file would end up if you do write it as is. Also very important: before creating the file, use the PHP function "umask," i.e. umask(077), so that files have their permissions locked down before they are created. This prevents someone from accessing the file before you have time to manually change the permissions.
  11.  
  12. Whenever a user logs in, use the PHP function "session_regenerate_id" to prevent fraudulent access to their account or a session-fixation attack.
  13.  
  14. More to come... Please post your own.

Report this snippet  

You need to login to post a comment.