JS Byte Array to File on PHP Side - javascript

I have a Uint8Array which have 10000 bytes on Javascript side.
var data = new Uint8Array(10000) ;
I want to send it to PHP and create a file with it:
$.ajax({
url:'saver.php',
type: 'POST',
contentType: 'application/octet-stream',
data:data,
processData: false
});
This ajax is sending data (I see it on "Request Payload" section on console) but there is no $_POST record, $_POST array is empty, just silent. How to grab it properly?

This seems to be a known behavior.
For an array of 10000 bytes, you should be able to use
$rawPost = file_get_contents('php://input');
to get your data from the request instead of checking the $_POST variable.
Note that this method loads the data in-memory, so if the data are too large, you will get an error.

In my case.
I get binary file from JS request array : $file['content'] format of Uint8Array.
<?php
$packed = pack("c*", ...$file['content']);

Related

json_decode expects parameter 1 to be string, says array is given. Why doesn't my string pass properly?

So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.
The data I send through the ajax call is, according to console.log(noBrack):
{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}
My Ajax call is:
$.ajax({
url: 'quickGrade.php',
type: 'POST',
data: noBrack,
datatype: 'json',
success:function(data){
alert(data );
}
});
My PHP code is:
$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);
Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.
The way you are sending data will give you $_POST array in php code. So actually you do not need to decode because the data is coming as $_POST array not a JSON string.
You should use json_encode to get JSON string to store in file. Because $_POST is an array, so you can't decode it like a Json string.
Your code will become this:
$testSave = 'data/gradeTest.json';
file_put_contents($testSave, json_encode($_POST));
You can read more about:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php

Access array posted with Javascript

I'm using the following code to send a form to a php processor:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
I presume that this sends the form to my php script with all the form values in json format but I then don't know how to then access this json and turn it back into the array i need to process in my PHP script.
Does anyone know how I access this variable in my processor script so I can process the data?
Also, what is the best way for me to view the data being posted so I can work out what to do with it, when I send the data the processor is obviously not displayed, is there a way to echo out/write the information received by the script to I can view it?
You can easily access to the json as an array called "$_POST" in your php.
for example, if you send the form as a json structured like this:
{
"name":"userID",
"psw":"password123"
}
in your php script there will be the variable $_POST with this structure:
$_POST = Array (
"name" => "userID",
"psw" => "password123"
)
EDIT
In a comment you asked me how to display the data received from the server,
that's quite simple,
in your php script just write this:
echo json_encode($_POST);
so that you output the $_POST array in the json format,
then in your script write this:
$.post($(this).attr('action'), $(this).serialize(),
function(data){ //"data" argument will contain the output from the server (that is the encoded $_POST array printed as json with the php code as showed above)
console.log(data); //log data
}
); //as you can see, I've deleted "json", becouse it's unuseful

Ajax Post dataURL using multipart/form-data

I am am writing a program that pulls a dataURL from a canvas element and sends it server side to be converted back to a jpg and saved. What I need to do now, is to programmatically get this image from the server and post it using another ajax function as a multipart/form-data encoded form. There is some code that cannot be modified and it is expecting this type of post.
To be specific: how do I take an image from the server and put it into a POST of enctype="multipart/form-data" such that the code receiving the request sees it as if it were an post coming from a regular form. All of this using Jquery or JavaScript Ajax.
Extra info: The code being posted to is in ASP classic. I am using PHP to convert the DataURL.
PHP Code:
//Get the base-64 string from data
$data=$_POST['img_val'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('filename.png', $data);
$images_orig = imagecreatefrompng('filename.png');
$photoX = ImagesX($images_orig);
$photoY = ImagesY($images_orig);
$images_fin = ImageCreateTrueColor(650, 650);
ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, 650+1, 650+1, $photoX, $photoY);
imagejpeg($images_fin, NULL, 100);
ImageDestroy($images_orig);
ImageDestroy($images_fin);
The above code can be use to return either a binary Image File or to save the contents to disk and return an image URL. I'm not sure which will be more useful to my end goal.
Thanks to All.
So for those who need a solution to something like this, the answer is a bit complicated. The above PHP code does properly convert the image from a dataURL to a png, and then resizes it as a jpg. The proper way to make a multipart/form-data Post from ajax goes like this:
var url = "example.php"
var image_as_blob = previousAjaxRequest(); //use xhr.responseType = "blob" and a GET request to grab server image
var form = new FormData();
form.append('image_variable_name', image_as_blob, 'file_name.extension'); //the third argument seemed to make all the difference in server code seeing the file correctly.
$.ajax({
url: url,
type: 'post',
data: form,
cache: false,
contentType: false, //required for multipart
processData: false //required for multipart
}).done(function( data ) {
//do what you want with returned data
});

file_get_contents('php://input'); with application/x-www-form-urlencoded;

I've read a few questions about the subject here on but couldn't find the answer I'm looking for.
I'm doing some $.post with jQuery to a PHP5.6 server.
$.post('/', {a:100, b:'test'}, function(data){
}, 'json');
The encoding from the console is
Content-Type application/x-www-form-urlencoded; charset=UTF-8
If I try to read the POST data with a regular $_POST, PHP5.6 alerts me
PHP Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead
So then I've tried the suggestion, added always_populate_raw_post_data = -1 in php.ini and
json_decode(file_get_contents("php://input"));
PHP5.6 alerts me that it is invalid
PHP Warning: First parameter must either be an object or the name of an existing class
So I've dumped file_get_contents("php://input") and it's a string.
a=100&b="test"
So I've parsed the string and encoded then decoded
parse_str(file_get_contents("php://input"), $data);
$data = json_decode(json_encode($data));
var_dump($data);
And THEN I finally have my $data as an object and not an array, as a true JSON object.
I've resorted to keep on using $_POST for now... But then I'm wondering about upgrading PHP..
The question here is that, is there a straighter forward solution to this or does it mean using file_get_contents("php://input") also means doing the parsing decoding encoding shenanigans?
Edit: so it appears this doesn't work either on multi levels json's.
Consider the following:
{"a":100, "b":{"c":"test"}}
As sent in Ajax/Post
{a:100, b:{c:"test"}}
Doing
parse_str(file_get_contents("php://input"), $post);
var_dump($post);
Will output
array(2) {
["a"]=>string(8) "100"
["b"]=>string(16) "{"c":"test"}"
}
Or doing (as suggested)
parse_str(file_get_contents("php://input"), $post);
$post= (object)$post;
Will output
object(stdClass)#11 (2) {
["a"]=>string(8) "100"
["b"]=>string(16) "{"c":"test"}"
}
How do I transform file_get_contents("php://input") into a true object with the same "architecture" without using a recursive function?
Edit2 : My mistake, the suggested worked, I got side tracked in the comments with JSON.stringify which caused the error.
Bottom line: it works with either json_decode(json_encode($post)) or $post=(object)$post;
To recap, using jQuery $.post :
$.post('/', {a:100, b:{c:'test'}}, function(data){
}, 'json');
parse_str(file_get_contents("php://input"), $data);
$data = json_decode(json_encode($data));
or
parse_str(file_get_contents("php://input"), $data);
$data= (object)$data;
No need to use JSON.stringify
Receiving serialized/urlencoded POST data in the request's POST body as you are, you've correctly transformed it into an array with parse_str() already.
However, the step of encoding then decoding JSON in order to transform that into the object (as opposed to array) you're looking for is unnecessary. Instead, PHP will happily cast an associative array into an object of class stdClass:
parse_str(file_get_contents("php://input"), $data);
// Cast it to an object
$data = (object)$data;
var_dump($data);
A little more information is available in the PHP documentation on type casting.
In order to send raw json data, you have to stop jQuery from url-encoding it:
data = {"a":"test", "b":{"c":123}};
$.ajax({
type: 'POST',
url: '...',
data: JSON.stringify(data), // I encode it myself
processData: false // please, jQuery, don't bother
});
On the php side, just read php://input and json_decode it:
$req = file_get_contents("php://input");
$req = json_decode($req);
My mistake, the suggested worked, I got side tracked in the comments with JSON.stringify which caused the error. Bottom line: it works with either json_decode(json_encode($post)) or $post=(object)$post;
The answer Michael gave is correct but side tracked me and I left the error in my code. JSON.stringify is only useful when posting the data from a form as I replied in the comment.

angular file upload converting data/payload into string

I have been using ng-file-upload to upload files to server. Recently I saw that it is converting payload/data that I am adding to it apart from file from any data type to string only. For example if I am sending integer or boolean field, it is converting it into string.
I am using django at backend, so when I print type of request data it is showing unicode and in model I have defined NullBooleanField. Because of this everytime it takes it True and save it in database as True. Below is the little snippet of what I am doing.
var _data = {'name': 'xxx',' good':false};
$scope.upload = $upload.upload({
url: URL,
method: 'PUT',
file: data_file,
data: _data,}).progress(function(evt){
});
each time when I print the type of this at backend
type(print (request.DATA['good'])))
it return
<type 'unicode'>
Am i missing something here or something is actually wrong?

Categories

Resources