Best practice escape special data

I am having issues with data that keeps breaking my JSON array.

Problem is that there is data which is entered manually by end users in a separate system and they keep entering bad data which breaks the JSON. Each time I find it, I implement a fix to escape the data but it keeps occurring (new data that apparently isn’t escaped)

I am using PHP to generate the JSON string.
I was using json_encode() for the manually entered fields but this missed some special characters, so I added htmlentities() but now a backslash has made its way into the data and I need to add another function to strip that character…

Just wondering if there is a best practice for this because I’m thinking json_encode( htmlentities( stripslashes($data) ) ) is probably not the most economical way of producing the correct data format…

json_encode should handle special characters. Do you have any examples of the input your code is tripping up on? A listing of exactly what you’re currently doing with the input would also help.

1 Like

To me it sounds like you are putting escape data into you database table? If you are using prepared statements you really do have to worry about escaping the data to the table. Personally I would just send the data using json_encode() then stanitize the output with php if you think it is necessary.

Sponsor our Newsletter | Privacy Policy | Terms of Service