While writing any web application in PHP, you need to be careful. As it is said, with great power comes great responsibility, so you need to safeguard yourself against the common security pitfalls when coding in PHP. These are not the faults of the PHP language or the MySQL database system. Its a responsibility of the developer to make the code secure against these.
1. Securing the password
Never store the passwords directly in a database. If you do that and the database is hacked, you risk giving away your user account’s details. Instead use one way encryption or hashing algorithms to hash your passwords. It is always very difficult to reverse hash a password. For example the following code:
$passwd = $_POST['passwd']; $salt = 'h3#gj^5'; // some random stuff. Or even better generate this random sequence on the fly with a specialised function. That way you will get different salt each time. $hash = crypt($passwd, $salt);
The salt here is any random stuff just to complicate the original password before hashing. Then store the hash and the salt in your database. That should make it a bit difficult for the hacker to do his job. During login you can recalculate the hash using the entered password and the stored salt to check if it matches the originally stored hash in your database.
2. Bypassing SQL Injection
Everybody has heard of SQL Injection. Its a relatively easy exploit but can wreck databases. You should always safeguard your PHP scripts against it. PHP even provides an inbuilt function to prevent it. All you need to do is to prevent it.
$id = mysql_real_escape_string($_GET['id']);
This function converts if any injection code is present in the parameter, to a non harmful escape sequenced form.
3. Save yourself from the null byte
The null byte is a dangerous thing. If introduced in a string it will trick the system to ignore any data that is followed after the null byte. Like for example,
$file = $_GET['file']; require_once("/var/www/$file.php");
All though the above script looks secure because it always enforces the .php extension after the file parameter. But it can be exploited by index.php?file=../../etc/passwd%00 , causing the .php part to be ignored, thus showing the system file /etc/passwd
To safeguard against this kind of exploit you should do this:
$newstring = $str_replace(chr(0), '', $string)
Thats it! Though the above mentioned methods are not the be all and end all of security but still they will make your site relatively secure.