I\'m trying to record data that is being posted to my server to a text file. An example of the data that is being sent to my server is located here:
http://dev.data
You are trying to save an object, using file_put_contents. While data
parameter this function "Can be either a string, an array or a stream resource"
http://php.net/manual/en/function.file-put-contents.php
Look at this example:
<?php
$json = '
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
';
$phpObj = json_decode($json);
var_dump($phpObj);
$myFile = "testFile.txt";
file_put_contents($myFile, $phpObj);
?>
It parses json correctly, but doesn't save anything as well, because php doesn't know, how to serialize $phpObj object.
You need to save raw JSON string:
<?php
$myFile = "testFile.txt";
file_put_contents($myFile,$_POST['json']);
echo '{ "success": true }';
?>
Then you can read the file and parse it if necessary.
I think you want to get the raw content of the POST, This works for me with both POST and PUT:
$phpObj = json_decode(file_get_contents("php://input"));
$_POST
contains the array from x-www-form-urlencoded
content, not json.
Hope that points you in the right direction :)
Edit: @user4035 is right... your also trying to save a php object to a file... This is what i would do:
<?php
$jsonString = file_get_contents("php://input");
$myFile = "testFile.txt";
file_put_contents($myFile,$jsonString);
echo '{ "success": true }';
?>
To bypass the problem I used JSON.stringify.
'formSave' : function(project){
var s = {
"name": project.name,
"data": JSON.stringify(project.data)
};
$.post("sdcform/formSave/" + project.name, s);
}
The 'project' object contains the keys 'name' and 'data' and I only wanted to stringify the data part of it.
This way on the server I can do
$data = isset($_POST['data']) ? json_decode($_POST['data']): new \stdClass();
file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT));
I could store it directly to the file and save both conversion but I wanted to prettyfy it!
Note: Yes I know! Do not access $_POST directly.