Question

I noticed the function json_encode() automatically puts backslashes on " and ' values. I was originally protecting against SQL injections by using mysqli_real_escape_string($con, $value) before the string was put into the array, after then it would be encoded using jSON.

Because json_encode adds the additional back slashes, it is necessary to use the mysqli_real_escape_string function?

Was it helpful?

Solution

Yes, it is still necessary. json_encode adds backslashes to the strings contained within the JSON, but not to the control elements of the JSON itself.

So, this:

array( 'key' => 'some "value" here' );

Becomes:

{"key": "some \"value\" here"}

There are still quotes in the string that are not escaped (the quotes surrounding the keys and values. json_encode is not meant to protect against SQL injection. It adds slashes purely for the JSON, so that when you, later on, json_decode() the data, it knows where the strings start and stop.

As others have said - use prepared statements. Period. If you're already using mysqli you have no reason not to.

OTHER TIPS

If you are using mysqli, just use Prepared Statements and you're done.

Neither json_encode() nor mysqli_real_escape_string() does protect against SQL injection.

Moreover, if you wouldn't use mysqli_real_escape_string() in your json encoded values, you'll be unable to decode them back.

Also, if you're storing json in your database, your database structure is wrong.

Tables you're using you your databases are such arrays. They are intended to store scalar values in their cells.

json_encode is insufficient protection against XSS or the generation of SQL errors. The act of encoding an object as JSON will even add new quote characters.

… but don't use mysqli_real_escape_string, use prepared statements and parameterized queries.

… and generally you shouldn't be storing JSON in a database. Normalise your data so you can query it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top