title: PHP Encrypt Streamed File From Javascript
body: <p>I am developing a File Uploader for big file. Upload from HTML script and send by byte from Javascript using ArrayBuffer and Unit8Array to PHP. The PHP script will stream the file and save it into folder.</p>
  
  <p>Here's my Javascript looks like</p>
  
  <pre><code>function upload(fileInputId, fileIndex)
      {
          var file = document.getElementById(fileInputId).files[fileIndex];
          var blob;
          var reader = new FileReader();
          reader.readAsBinaryString(file); 
          reader.onloadend  = function(evt)
          {
              xhr = new XMLHttpRequest();
  
              xhr.open("POST", 'upload.php?name=' + file.name, true);
  
              XMLHttpRequest.prototype.mySendAsBinary = function(text){
                  var data = new ArrayBuffer(text.length);
                  var ui8a = new Uint8Array(data, 0);
                  for (var i = 0; i &lt; text.length; i++){ 
                      ui8a[i] = (text.charCodeAt(i) &amp; 0xff);
  
                  }
  
                  if(typeof window.Blob == "function")
                  {
                       blob = new Blob([data]);
                  }else{
                       var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
                       bb.append(data);
                       blob = bb.getBlob();
                  }
  
                  this.send(blob);
              }
  
              var eventSource = xhr.upload || xhr;
              eventSource.addEventListener("progress", function(e) {
                  var position = e.position || e.loaded;
                  var total = e.totalSize || e.total;
                  var percentage = Math.round((position/total)*100);
              });
  
              xhr.onreadystatechange = function()
              {
                  if(xhr.readyState == 4)
                  {
                      if(xhr.status == 200)
                      {
                          console.log("Done");
                      }else{
                          console.log("Fail");
                      }
                  }
  
  
              };
  
              xhr.mySendAsBinary(evt.target.result);
          };
      }
  </code></pre>
  
  <p>This is my upload.php</p>
  
  <pre><code>$inputHandler = fopen('php://input', "r");
  $loc = "uploads/" . $_GET["name"];
  $fileHandler = fopen($loc, "w+");
  
  while(true) {
      $buffer = fgets($inputHandler, 4096);
  
  
  
      if (strlen($buffer) == 0) {
          fclose($inputHandler);
          fclose($fileHandler);
          return true;
      }
  
      fwrite($fileHandler, $buffer);
  }
  </code></pre>
  
  <p>My question is, how do I encrypt those upload file using AES or mcrypt while the file is in streaming mode?</p>