I'm using file_get_contents('php://input')
to retrieve all the POST parameters/values from a particular web service, e.g.:
$postText = file_get_contents('php://input');
which results in something like this:
inReplyToId=MG1133&to=61477751386&body=test&from=61477751386&messageId=166594397&rateCode=
I then need to get each of the individual key/value pairs as I need to set them into fields in a new database record. For example I would like to end up with:
$inReplyToId = MG1133
$to = 61477751386
$body = test
Once I know the individual value I can set the corresponding field in the database. I would normally use:
if(isset($_POST['inReplyToId']) && $_POST['inReplyToId'] !== '' ) {
$request->setField('_kf_GatewayMessageID', $_POST['inReplyToId']);
}
But that won't work in this case as it's not a application/x-www-form-urlencoded
form that is being submitted.
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.
The file_get_contents() function reads entire file into a string. The file() function reads the entire file in a array, whereas file_get_contents() function reads the entire file into a string.
file_get_contents() is slightly faster than cURL.
file_get_contents in itself appears safe, as it retrieves the URL and places it into a string. As long as you're not processing the string in any script engine or using is as any execution parameter you should be safe.
You can use parse_str
function to parse query string:
$queryString = 'inReplyToId=MG1133&to=61477751386&body=test&from=61477751386&messageId=166594397&rateCode=';
$data = array();
parse_str($queryString, $data);
var_dump($data);
Edit:
For example I would like to end up with:
$inReplyToId = MG1133 $to = 61477751386 $body = test
To get array keys as variable you can use extract
:
extract($data);
Edit 2: If you already have code that uses $_POST
variable with respective indexes you can merge data with it:
$_POST = array_merge($data, $_POST);
But modifing these variables is not advisable.
Take a look at the parse_str() function, which coverts a parameterized string, into an associative array.
You can use this code! try!
<?php
$postdata = file_get_contents("php://input");
//$postdata = '{"mail": "[email protected]", "number": 6969 }';
$obj = json_decode($postdata);
echo $obj->{'mail'}; // [email protected]
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With