2

Let's say I have a PHP script that has a bunch of binary data in it that needs to be processed client side in JavaScript.

<?php
$binary_data = file_get_contents( "file.data" );
?>

And I have a JavaScript function that is meant to process it from an ArrayBuffer:

<script type="text/javascript">
function processData( arrayBuffer ) {
...
}
</script>

Passing it directly won't work because it's binary data so this won't work:

<?php

$binary_data = file_get_contents( "file.data" );

echo <<<EOF

<script type="text/javascript">

var binaryData = '{$binary_data}';

processData( binaryData );

function processData( arrayBuffer ) {
...
}
</script>

EOF;

?>

How can I pass the PHP variable $binary_data into a JavaScript variable ArrayBuffer in a single page load?

Mikey A. Leonetti
  • 2,834
  • 3
  • 22
  • 36

1 Answers1

2

I just ended up converting the data to base64 and then using it in my code. I thought that maybe I could also directly make an array buffer and initialize it with numeric bytes, but that would end up being a lot longer in the HTML. I figured base64 would be the "cheapest" amount of bytes based on this post (Base64: What is the worst possible increase in space usage?).

Then I needed to convert the base64 directly to an ArrayBuffer. I found this little gem (https://gist.github.com/borismus/1032746) which I modified a bit for what I did.

The final code (based on the original):

<?php

$binary_data = base64_encode( file_get_contents( "file.data" ) );

echo <<<EOF

<script type="text/javascript">

var binaryData = base64ToArrayBuffer( '{$binary_data}' );

processData( binaryData );

/**
 * Process the binary data ArrayBuffer
 */
function processData( arrayBuffer ) {
...
}

/**
 * Convert a base64 string to an ArrayBuffer
 */
function base64ToArrayBuffer( base64 ) {
    var raw = window.atob( base64 );
    var rawLength = raw.length;
    var array = new Uint8Array( new ArrayBuffer(rawLength) );

    for( i = 0; i < rawLength; i++ ) {
        array[ i ] = raw.charCodeAt( i );
    }
    return( array.buffer );
}

</script>

EOF;

?>
Community
  • 1
  • 1
Mikey A. Leonetti
  • 2,834
  • 3
  • 22
  • 36