Escaping user input necessary if using json_encode?


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.


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

Here’s a demo:

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



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.

Answered By – Bill Karwin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published