1

I have read about this and people ask this a bit too often.

lets say u have a input

$_POST['json_txt'] = "{
  bar:'value 1',
  foo:{
    baz:'value 2',
    fuz:'value 3'
  }
}";

We can validate this input using the php function json_last_error ();

Q 1 = Shouldn't there be another option where we can sanitise this json object?

Q2 = Also is the json_last_error(); the absolute way to correctly validate the input and save it to a db (mysql)?

3
  • 1
    You could also check if json_decode returns null, meaning it's invalid. Commented Jan 13, 2011 at 12:29
  • nice one, just realised that json_last_error (); only works on php 5 >=5.3.0 Commented Jan 13, 2011 at 12:37
  • I see you already have your answer, but you don't need to worry about sanitizing JSON on the PHP side the same way you do on the JS side. On the JS side, if you just eval() (which you shouldn't be doing anyway) the string, and it contains something malicious, it will be eval()ed. PHP actually deserializes the string into a structure (if it can). Commented Jan 13, 2011 at 12:58

1 Answer 1

1

Are you saving the entire JSON object to the database, or individual parts? You can sanitize a variable (either one from the decoded JSON object or the JSON object itself) with mysql_real_escape_string() before inserting it into the database.

Sign up to request clarification or add additional context in comments.

2 Comments

of course i have done that :) but what i meant is to check that there are no weird characters and things like that or do we just use regex so we only allow valid and the characters you expect. also yes, i am putting the json object as a whole :)
So you need to know whether the object is a valid JSON object? You can test that with the return vanlue of json_decode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.