PHP's security problems stem from bad code, not because PHP is a bad language. It just gives you enough rope to hang yourself. There are many excellent references available (online and books) that deal with best security practices for writing PHP code. This is only a very brief discussion of a few security considerations. For a more in depth coverage of the subject please download and read the PHP Security Consortium's free PHP Security Guide. I personally feel the earlier you are aware of security concerns--the better.
DB Access Credentials
Database access credentials should NEVER-- repeat NEVER-- be in the web root. Need a reason why not? Go here: http://www.google.com/search?q=inurl%3Adb.inc (originally shown in Chris Shiflett's blog). If your access information is in the web root, potentially anyone can get a hold of it and play merry cob with your database. If that happens then any personal data and passwords can be stolen. I personally prefer to keep all my access information (DB, password files, configuration files) in a misc or access folder along side the web root--not in it. Then I just include them into the script.
Validate Input
NEVER, NEVER, NEVER trust user input. Do I need to say it again? Never trust user input. I won't get in to all the reasons why not, but I will say that getting "bad" data from users can cause huge problems for your script. So what do we do now, since we don't trust user input? We validate everything they give us. PHP has a number of functions available to help you. Unfortunately I don't have the time (and space) to go over them all so I will just quickly point out a few options in an example. Make sure you check out the functions in the example and any of their related functions.
Hmm-- still missing the regular expression functions, the checkdate() function and probably a few others... but I think you get the whole idea.
Escape Output
Why escape output when you are so diligently validating input? Well no matter how smart we are (or think we are), someone is always smarter. So if something does get by our input filtering, we want to make sure it can't actually do anything when the page is displayed/loaded (such as someone defacing your page or having some nasty JavaScript running). So how do you escape output? Well addslashes(), urlencode(), and htmlentities() are a good places to start:
<?php $query = sprintf("INSERT INTO myTable (comments) VALUES('%s')", mysql_real_escape_string($comments)); echo "The following comment will be added to the database:<br />"; echo htmlentities($content); ?>
.Initializing Variables
Simply put-- if you don't initialize a variable, some one else will leading to bad things and huge security holes. This includes variables that may come into your script--say your post and get variables for example. If you use a temporary variable in your script, make sure you give it a value. Use a ternary for post, get and request variables.