title: ajax php file upload without iFrame or flash engine
body: <p>I've simplified my code for uploading a file without iFrame or flash engine, and i came up to this ajax function:</p>
  
  <pre><code>&lt;input type="file" name="uploadfile" id="myfile" /&gt;&lt;label for="file" id="progress"&gt;&lt;/label&gt;
  
      &lt;script src="js/jquery-1.7.1.min.js"&gt;&lt;/script&gt;
      &lt;script&gt;
  
      function uploadFile(files) {
  
          var xmlhttp;
          if(window.XMLHttpRequest)
              xmlhttp = new XMLHttpRequest();
          else
              xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  
          xmlhttp.upload.onprogress = function(e) {
              $("#progress").empty().append(e.loaded + " - " + e.total);
          }
  
          xmlhttp.onreadystatechange = function() {
              if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
                  alert(xmlhttp.responseText + "DONE!");
              }
          }
  
          xmlhttp.open("post", "post.php", true);
          xmlhttp.setRequestHeader("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
          xmlhttp.setRequestHeader("Cache-Control", "no-cache");
          xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
          xmlhttp.setRequestHeader("X-File-Name", files[0].fileName);
          xmlhttp.setRequestHeader("Content-Type", "multipart/form-data");
          xmlhttp.send(files[0]);
      }
  
  
  
      $(document).ready(function() {
  
          $("#myfile").change(function() {
              uploadFile(this.files);
          });
  
      });
  
      &lt;/script&gt;
  </code></pre>
  
  <p>This is the php code which reply to the ajax function: </p>
  
  <pre><code>&lt;?php
  if(isset(
          $_SERVER['CONTENT_TYPE'],
          $_SERVER['CONTENT_LENGTH'],
          $_SERVER['HTTP_X_FILE_NAME']
      ) &amp;&amp;
      $_SERVER['CONTENT_TYPE'] == 'multipart/form-data'){
  
          $file-&gt;name = basename($_SERVER['HTTP_X_FILE_NAME']);
          $input = fopen('php://input', 'rb');
      $file = fopen('files/'.$file-&gt;name, 'wb');
      stream_copy_to_stream($input, $file);
      fclose($input);
      fclose($file);
      } else {
  
      echo "Error";
      }
  ?&gt;
  </code></pre>
  
  <p>The problem is, sometimes it works sometimes it bugs up while trying to upload the same file. I hope there is a solution to fix this issue. The code is simple, when i choose a file with input file type, the uploadFile function executes.
  When it bugs out, i can see the file starting to be uploaded but it doesnt have the original size, so somewhere it could bug and stop uploading.</p>
  
  <p>Thank you in advance, Daniel!</p>