Search code examples
phpsqljsonsql-injectionmysql-real-escape-string

Does json_encode() protect against SQL injections?


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?


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.