I am using following code lines in order to protect injections or the like for login via PHP script. Kindly let me know will it be enough to be safe from the attack or I have to add some more lines to make the code more secured.
// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
In theory that should be safe enough, however there are still several problems with it.
mysql_real_escape_string is deprecated - you should not use them, but a prepared statement.
You are not hashing the password - it is not a good idea to store plain text passwords, as if the database is compromised, they will all be immediately known. PHP has a dedicated password_hash function which you can use instead.
Why are you stripping slashes? If you are expecting the input username might contain slashes, then you are missing a validation step somewhere else. In general, it is better to use whitelists than blacklists - i.e. instead of trying to strip out bad characters, have a list of good characters and only allow those. That way you can secure your username/password with something simple, like preg_replace('#[^a-bA-B0-9]#', '', $username)
Using any mysql_*
functions is not entirely secure. That family of functions is now deprecated.
You should look at using MySQLi or PDO with prepared statements for the absolute security...
If you know what you are doing, mysql_* functions are still good to use, though they have been deprecated. Just be sure you don't let in a injection vulnerability. mysql_* functions are deprectated because it is too easy to let such vulnerabilities in. Other function libraries such as mysqli_* and PDO_* allow for parameterized queries, that makes it easier to write secure code.
Be aware off course that you have absolutely no guarantee that deprecated functions will still exist in newer versions of PHP.
They lines you stated are too much. Only mysql_real_escape_string()
is needed. You can remove strip_slashes()
.