You have the basic idea already.
you should test that the value is set and also strip extra slashes from the incoming string before trying to parse it as JSON.
if(isset($_POST['data'])){
$array = json_decode(stripslashes($_POST['data']),true);
//$array now holds an associative array
}//Data Exists
It also would not be a bad idea before you start working with the array to test that the call to json_decode()
was successful by ensuring that $array
isn't null
before use.
If you do not fully trust the integrity of the information being sent you should do extended checking along the way instead of trusting that a given key exists.
if($array){ // Or (!is_null($array)) Or (is_array($array)) could be used
//Process individual information here
//Without trust
if(isset($array['Firstname'])){
$CustomerId = $array['Firstname'];
}//Firstname exists
}//$array is valid
I in-particular like to verify information when I am building queries dynamically for information that may not be required for a successful db insert.
In the above example $_POST['data']
indicates that what ever called the PHP script did so passing the JSON string using the post
method in a variable identified as data
.
You could check more generically to allow flexibility in the sending method by using the $_REQUEST
variable, or if you know it is coming as via the get
method you can check $_GET
. $_REQUEST
holds all incoming parameters from both get
and post
.
If you don't know what the name of the variable coming in is and want to play really fast and loose you could loop over the keys in $_REQUEST
trying to decode each one and use the one that successfully decoded (if any). [Note: I'm not encouraging this]