You write this:
$sql = "SELECT id_user, name FROM 'TAB_USER' WHERE user = '$username'
^^^^^^^^^
SQL injection is here
The bad guy will send as "username" something which will, after replacement, make your SQL command look like this:
SELECT id_user, name FROM 'TAB_USER' WHERE user = 'Admin'; -- (some stuff here)
i.e. the attacker will set the "username" to the string: Admin'; --
See the nifty quote character ? That's the lever for the attack. Since your code brutally replaces $username
in the SQL command, with "whatever the client provided", the client can provide a closing quote character, which terminates the string constant, then a semicolon, which terminates the command, then a --
which tells to the database "everything else on the line is a comment, just ignore it". And ignore it the database does !
This allows the attacker to log in as admin regardless of whatever password he used. This is textbook SQL injection. Please take note: you may be tempted to conclude that the problems come from the "quote" character, and simply filtering out would be sufficient to avoid the attack. This is not so. There are several (many) ways to abuse a brutal replacement such as the one you do, and it is very hard to catch them all; like Pokemons, each new version of the SQL database software introduces new species. People tried to think of SQL injection as an "escape troublesome characters" issue; so they designed this function. Then they tried again. And it still failed. Only sorrow awaits you on this path; don't walk it. Don't wait for a mysql_really_escape_string_this_time_i_said_please()
. Instead, use prepared statements.