addslashes and json_encode not working together

2.9k views Asked by At
$val = "I'm string";

For this type of string I am using the addslashes function, which convert string into like this:

"I\'m string"

and store into the database. When I get all data from database in array of fields and passed array in

json_encode($arr);

In response I get the string with a extra slash like this:

"I\\'m string"

And I wanted to remove that extra slash which is added by json_encode. how I do that??

3

There are 3 answers

4
Timmetje On BEST ANSWER

If you really want an answer to this question you can reverse your addslashes with stripslashes.

But never use addslashes function to escape values you are going to send to mysql.

Use native prepared statements, mysqli_real_escape_string() or PDO::quote.

BUT NOTE:

  1. Don't use a vulnerable character set for connection encoding (use utf8 or something)
  2. Use a higher version of MySQL than 5.7.6.

Read more about character set issues here: http://php.net/manual/en/mysqlinfo.concepts.charset.php

0
Script47 On

You can use stripslashes.

However, you should use prepared statements. That way you don't need to worry about escaping your values.

1
Loek On

It might even be possible with this (though I thought it was forward slash / only:

json_encode($array, JSON_UNESCAPED_SLASHES);

But heed to the comments and Script47's answer and just fix it properly.