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

/ Published in: PHP
Save to your folder(s)

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.

Copy this code and paste it in your HTML
  1. Regarding user input (e.g. web forms, but pretty much any possible user input):
  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.
  5. In PHP with MySQL, use the function "mysql_real_escape_string" when interacting with the database (db).
  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.
  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.
  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.
  14. More to come... Please post your own.

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.