<?php

/*******************************************************************
 * Get file sent by HTML5 FileReader/XHR
 *******************************************************************/
function get_xhr_file()
{
  $file_name = $_SERVER['HTTP_X_FILE_NAME'];
  $file_size = $_SERVER['HTTP_X_FILE_SIZE'];
  $file_type = $_SERVER['HTTP_X_FILE_TYPE'];
  $file_data = $_SERVER['HTTP_X_FILE_DATA'];
  $file_path = tempnam('/tmp', "");

  $content = file_get_contents('php://input');
  $content = str_replace(' ', '+', $content);
  if($comma_pos = strpos($content, ','))
  {
    $content = substr($content, $comma_pos + 1);
  }
  $content = base64_decode($content);
  file_put_contents($file_path, $content);

  // On php shutdown delete file
  register_shutdown_function('delete_xhr_file', $file_path);

  return array(
    'name' => $file_name,
    'size' => $file_size,
    'type' => $file_type,
    'path' => $file_path,
    'data' => ($file_data) ? json_decode(base64_decode($file_data)) : null,
  );
}

function delete_xhr_file($file_path)
{
  unlink($file_path);
}