I'm using Node.js to send binary data to PHP. The POST data contains a JSON string, followed by newline, then the binary part.
Sending data from Node:
let binary = null;
if('binary' in msg)
{
binary = msg.binary;
delete msg.binary;
}
let buf = Buffer.from(JSON.stringify(msg) (binary === null ? '' : '\n'));
if(binary !== null) buf = Buffer.concat([buf, binary]);
let response = await axios.post
(
url,
buf
);
...and receiving it in PHP:
$binary = null;
$in = file_get_contents('php://input');
$pos = strpos($in, "\n");
if($pos === false)
{
$_POST = json_decode($in, true);
}
else
{
$_POST = json_decode(substr($in, 0, $pos), true);
$binary = substr($in, $pos 1);
}
This works, but I'm getting a warning:
PHP Warning: Unknown: Input variables exceeded 1000.
Is there any way to prevent PHP from trying to parse the POST data?
CodePudding user response:
I just discovered PUT. It does exactly what I'm looking for. Just have to change axios.post(url, buf) to axios.put(url, buf). On the PHP side, there's no attempt to decode anything - it is up to the script to interpret the data.
CodePudding user response:
Separate file from json:
let formData = new FormData();
formData.append('file', fs.createReadStream(filepath));
formData.append('json', '{"jsonstring":"values"}');
axios.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
}).then((response) => {
fnSuccess(response);
}).catch((error) => {
fnFail(error);
});
And PHP
$jsonstring = $_POST['json'];
$json = json_decode($jsonstring,true); // array
$uploaddir = "path/to/uploads/";
$uploadfile = $uploaddir . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile))
{
$uploadfile // is the path to file uploaded
}
