Mysql Security
Mysql Security
The main security risk with PHP and MySQL working together is the user typing in something to a form which you did not want them to type.
Passwords - hashing
If user passswords are stored in plain text on the database server then anyone with access (administrator or hacker) will have some valuable data. To prevent this passwords should not even be stored in the database. This might sound strange but MD5() is a built-in MySQL function which will take any string (e.g. a password) and make a mess of it! The mess it makes cannnot, in theory, be reassembled into the password. In practice the methods used to "mess up" the data can be cracked but it is hard to do. MD5 (or SHA1 which is the main alternative) are very similar to encryption but are designed to be one way. The way to use them is therefore: 1. 2. 3. 4. process the password with MD5 store the result and not the password when the user types in their password process that in the same way compare the processed result stored with the one type in and if they match the password was correct
The MD5 function is called within the query every time the password data is INSERTed: $insertquery="INSERT INTO users (username, password) VALUES ('$username', MD5('$password'))"; or used in a WHERE: $selectquery="SELECT bankaccountnumber FROM users WHERE username=$username AND password=MD5('$password'))"; The big advantage is that even the database administrator cannot access user passwords. MD5 is not perfect (there are ways to reverse both it and SHA1) and so extra precautions may be advisable. One is to combine the MD5 checksum for the password (the name for the result) with another MD5 checksum to provide something which is a mix of two hashes and therefore is much harder to crack. This is a slightly awkward way of implementing the concept of a "salt" (explained below) which is not supported by MD5.
Conclusions
Always run POST or GET data through mysql_real_escape_string() and always put quotes around the variable inside the query. That makes you safe. Always hash passwords and encrypt data and then the data is safe. Copyright Martin Matthews 2010-2011, all rights reserved