-1

If I take some input from a user in $_POST and json_encode it

$json = json_encode($_POST);

and put it in the query

$save = mysqli_query($con, "INSERT INTO table (json) VALUES ('$json')");

Is this prone to SQL injection? Does this input needs to be escaped? In my tests, I couldn't run any queries with input like

') SELECT * FROM table; --

but I'm not even remotely good at this.

PS - This is a test for learning. I'm not actually doing this in a project.

Whip
  • 1,891
  • 22
  • 43

1 Answers1

1

For the record, yes it is vulnerable. json_encode() does not escape special characters except for ".

Here's a demo:

<?php
$a = [ "name" => "O'Reilly" ];
$j = json_encode($a);
echo "$j\n";

Output:

{"name":"O'Reilly"}

Now what would happen if you interpolated this into an SQL string?

You'd get an unescaped single-quote character inside a single-quoted SQL string literal, which causes a syntax error.

INSERT INTO table (json) VALUES ('{"name":"O'Reilly"}')
                                            ^

The advice in the comments above is correct: When in doubt, use query parameters. Then you don't have to worry about whether the string is safe.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828