Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does json_encode() protect against SQL injections? [duplicate]

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?

like image 410
Oliver Tappin Avatar asked May 05 '26 05:05

Oliver Tappin


1 Answers

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.

like image 102
Colin M Avatar answered May 07 '26 17:05

Colin M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!