Skip to content
Advertisement

Escaping user input necessary if using json_encode?

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

JavaScript

and put it in the query

JavaScript

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

JavaScript

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.

Advertisement

Answer

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

Here’s a demo:

JavaScript

Output:

JavaScript

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.

JavaScript

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement