title: HTML JS PHP File chunk upload
body: <p>I am working with a file chunking solution ( cant remember where I found it ) but I have modified the solution to my needs.
  The issue is that although most of the time the file will upload successfully sometimes I get an error</p>
  <blockquote>
  <p>Uncaught SyntaxError: Unexpected token &lt; in JSON at position 0</p>
  </blockquote>
  <p>I also get another error at the same time</p>
  <pre><code>( unlink(test/H2jig-6.png): Resource temporarily unavailable in ... )
  
  </code></pre>
  <p>I was hoping that you guys will be able to spot the issue in my code that is causing this problem. I think that it manages to unlink the files too early before the uploads are done and then is unable to find them.</p>
  <p>Upload file HTML/JS</p>
  <pre><code>&lt;!DOCTYPE HTML&gt;
  &lt;html lang=&quot;en-US&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;test upload by chunk&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;input type=&quot;file&quot; id=&quot;f&quot; /&gt;
  
    &lt;script&gt;
    function makeid() {
    var text = &quot;&quot;;
    var possible = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&quot;;
  
    for (var i = 0; i &lt; 5; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));
  
    return text;
  }
  
  
    (function() {
  
  var f = document.getElementById('f');
  
  if (f.files.length)
  processFile();
  
  f.addEventListener('change', processFile, false);
  
  
  function processFile(e) {
  var scount = 0;
  var file = f.files[0];
  console.log(file);
  var ext =  file.name.split('.').pop();
  ext = '.'+ext;
  var size = file.size;
  
  var sliceSize = 250000;
  var num_of_slices = Math.ceil(size / sliceSize);
  var fileid = makeid();
  var start = 0;
  
  setTimeout(loop, 1);
  
  function loop() {
    var end = start + sliceSize;
  
    if (size - end &lt; 0) {
      end = size;
    }
  
    var s = slice(file, start, end);
    scount ++;
    send(s, start, end,scount,size,num_of_slices,ext,fileid);
  
    if (end &lt; size) {
      start += sliceSize;
      setTimeout(loop, 1);
    }
  }
  }
  
  
  function send(piece, start, end,scount,size,num_of_slices,ext,fileid) {
  var formdata = new FormData();
  var xhr = new XMLHttpRequest();
  
  xhr.open('POST', 'uploadchunk2.php', true);
  
  formdata.append('start', start);
  formdata.append('end', end);
  formdata.append('file', piece);
  formdata.append('scount', scount);
  formdata.append('fsize', size);
  formdata.append('num_of_slices', num_of_slices);
  formdata.append('ext', ext);
  formdata.append('fileid', fileid);
  xhr.onreadystatechange = function() {
      if (this.readyState == 4 &amp;&amp; this.status == 200) {
          var myArr = JSON.parse(this.responseText);
          console.log(myArr);
          // myFunction(myArr);
      }
  };
  xhr.send(formdata);
  }
  
  /**
  * Formalize file.slice
  */
  
  function slice(file, start, end) {
  var slice = file.mozSlice ? file.mozSlice :
              file.webkitSlice ? file.webkitSlice :
              file.slice ? file.slice : noop;
  
  return slice.bind(file)(start, end);
  }
  
  function noop() {
  
  }
  
  
  })();
  
  
    &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  <p>PHP upload</p>
  <pre><code>&lt;?php
  
  
  $target_path = '/test/';
  
  $tmp_name = $_FILES['file']['tmp_name'];
  $filename = $_FILES['file']['name'];
  $target_file = $target_path.$filename;
  $num_chunks_uploaded = $_POST['scount'];
  $num_chunks_created = $_POST['num_of_slices'];
  $extension = $_POST['ext'];
  $file_id = $_POST['fileid'];
  $file_location = 'test/';
  $file_path = $file_location.$file_id.$extension;
  $chunked_file_path = $file_location.$file_id.'-'.$num_chunks_uploaded.$extension;
  move_uploaded_file(
      $_FILES['file']['tmp_name'],
      $chunked_file_path
  );
  
  
  
  
  // count amount of uploaded chunks
  $chunksUploaded = 0;
  for ($i=1; $i &lt;= $num_chunks_created ; $i++) {
    if ( file_exists($file_location.$file_id.'-'.$i.$extension) ) {
         ++$chunksUploaded;
    }
  }
  
  
  
  // when this triggers - that means the chunks are uploaded
  if ($chunksUploaded == $num_chunks_created) {
  
      /* here you can reassemble chunks together */
      for ($i = 1; $i &lt;= $num_chunks_created; $i++) {
  
        $file = fopen($file_location.$file_id.'-'.$i.$extension, 'rb');
        $buff = fread($file, 2097152);
        fclose($file);
  
        $final = fopen($file_path, 'ab');
        $write = fwrite($final, $buff);
        fclose($final);
  
        unlink($file_location.$file_id.'-'.$i.$extension);
      }
  }
  
  $data = $chunksUploaded;
  header('Content-Type: application/json');
  echo json_encode($_POST);
  
  
  
  
  
  
  
  
  
   ?&gt;
  </code></pre>