-2

I have the following code

$username=htmlspecialchars($_POST['username'],ENT_QUOTES);
$sql="SELECT * FROM user_account WHERE account_name='".$username."'";

Is this vulnerable to sql injection. If so, how could someone manage to bypass this?

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Matkey
  • 378
  • 4
  • 17
  • check `mysql_real_escape_string` – Vicky Gonsalves Jan 29 '16 at 15:36
  • 2
    Switch to PDO or MySQLi. Much better then MySQL and MySQL is gone as of PHP7 – Chris G Jan 29 '16 at 15:37
  • @vicky-gonsalves Thanks, but how is that better than htmlsepcialchars? – Matkey Jan 29 '16 at 15:38
  • @Matkey Because `htmlspecialchars` is for HTML, not SQL. – ceejayoz Jan 29 '16 at 15:39
  • 1
    Stop using the **deprecated and as of PHP7 removed** mysql_* functions. Migrate to PDO and start using Prepared Statements, it really isn't hard. – Charlotte Dunois Jan 29 '16 at 15:40
  • Of course, but I am still unable to come up with any input that would work as an sql injection for the above code. I believe my questions is not about how to fix it but rather as to why it is vulnerable in the first place? – Matkey Jan 29 '16 at 15:41
  • 2
    Here's why: http://stackoverflow.com/questions/22116934/is-htmlspecialchars-enough-to-prevent-an-sql-injection-on-a-variable-enclosed-in – Jack Jan 29 '16 at 15:57

1 Answers1

1

Use MySQLi like this

$username = mysqli_real_escape_string($con, $_POST['username']);
$con is your connection 

Read this as well

  1. SQL Injection Protection - single quotes
  2. How can I prevent SQL-injection in PHP?

and Advantages Of MySQLi over MySQL

Community
  • 1
  • 1
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85