Beyond $_POST, $_GET and $_FILE: Working with Blob in JavaScript and PHP


If you've ever built an HTML form and used a PHP script for the processing part, then you'll be used to the concepts of $_POST and $_GET. Also likely is that you are aware that it is possible to upload files to a server using a similar form and PHP combo.

The questions is how do we successfully upload/send data created using JavaScript to a PHP script when it is more than a small snippet of data.

JavaScript/jQuery

Let's pretend we've saved a JSON string to localStorage and that we want to send this as a Blob to a PHP script. In our JavaScript, we could write:


<!DOCTYPE html>
<html>
<head>

// We'll import the jQuery library
<script src="js/jquery.js"></script>

</head>
<body>

// We've retrieved data in some way, perhaps using jQuery getJSON()
$.getJSON("json.php", function(data) {

// We've then added the data to Local Storage
localStorage.setItem('json', JSON.stringify(data));

// Now let's presume the data has been manipulated and resaved
...

// And now we're ready to retrieve the json and send it back to the server
var jsonstring = localStorage.getItem('json');

// The question is what's the best way. If it's more than a small snippet then $_POST and $_GET might fail us, so instead we use a Blob

var oReq = new XMLHttpRequest();

var url ="json_data.php"

oReq.open("POST", url, true);
oReq.onload = function (oEvent) {
  // Uploaded.
};

var blob = new Blob([jsonstring], {type: 'text/plain'});
oReq.send(blob);

// The above code is copied almost word for word from the Mozilla site.

});

</body>
</html>

PHP Script

Now what about on the other end where we receive the data? Here you go:

<?php

// choose a filename
$filename = "hello.json";

// the Blob will be in the input stream, so we use php://input
$input = fopen('php://input', 'rb');
$file = fopen($filename, 'wb');

// Note: we don't need open and stream to stream, we could've used file_get_contents and file_put_contents
stream_copy_to_stream($input, $file);
fclose($input);
fclose($file);

?>


To get things working simply, that's all there is to it.

Further reading

Local Storage (Smashing Magazine, JavaScript)

Blob (Mozilla, JavaScript)

File Upload (PHP.net)

stream_copy_to_stream (PHP.net)

'Saving generated files on the client-side' (HTML5 Rocks)

Comments