upload-files-to-php-backend-using-fetch-formdata

PHP is a good server side scripting language to kickstart project. In this post, we will see how to upload files to PHP backend using fetch and FormData.

As we have already discussed the fetch APIs in the post GoodBye XMLHttpRequest; AJAX with fetch API; we will look into PHP backend code to accept the File Uploads.

In general Form via POST and mutipart-formadata, following code will handle image file upload: (primary idea taken from PHP: Handling file uploads - Manual)

<?php
header('Content-Type: application/json; charset=utf-8');
$response = array();
try {
  
  // Undefined | Multiple Files | $_FILES Corruption Attack
  // If this request falls under any of them, treat it invalid.
  if (
    !isset($_FILES['upfile']['error']) ||
    is_array($_FILES['upfile']['error'])
  ) {
    throw new RuntimeException('Invalid parameters.');
  }

  // Check $_FILES['upfile']['error'] value.
  switch ($_FILES['upfile']['error']) {
    case UPLOAD_ERR_OK:
      break;
    case UPLOAD_ERR_NO_FILE:
      throw new RuntimeException('No file sent.');
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
      throw new RuntimeException('Exceeded filesize limit.');
    default:
      throw new RuntimeException('Unknown errors.');
  }

  // You should also check filesize here. 
  if ($_FILES['upfile']['size'] > 1000000) {
    throw new RuntimeException('Exceeded filesize limit.');
  }

  // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
  // Check MIME Type by yourself.
  $finfo = new finfo(FILEINFO_MIME_TYPE);
  if (false === $ext = array_search(
    $finfo->file($_FILES['upfile']['tmp_name']),
    array(
      'jpg' => 'image/jpeg',
      'png' => 'image/png',
      'gif' => 'image/gif',
    ),
    true
  )) {
    throw new RuntimeException('Invalid file format.');
  }

  // You should name it uniquely.
  // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
  // On this example, obtain safe unique name from its binary data.
  if (!move_uploaded_file(
    $_FILES['upfile']['tmp_name'],
    sprintf('./uploads/%s.%s',
      sha1_file($_FILES['upfile']['tmp_name']),
      $ext
    )
  )) {
    throw new RuntimeException('Failed to move uploaded file.');
  }
  $response = array(
    "status" => "success",
    "error" => false,
    "message" => "File uploaded successfully"
  );
  echo json_encode($response);

} catch (RuntimeException $e) {
  $response = array(
    "status" => "error",
    "error" => true,
    "message" => $e->getMessage()
  );
  echo json_encode($response);
}

Let see the JS and relevant HTML to send file to above code:

HTML:

<form method="POST" action="upload.php" id="profileData" enctype="multipart/form-data">
  <div class="form-row">
    <div class="col">
      <div class="form-group">
        <label for="firstName">First Name</label>
        <input name="firstName" type="text" id="firstName" class="form-control" placeholder="First name">
      </div>
    </div>
    <div class="col">
      <div class="form-group">
        <label for="lastName">Last Name</label>
        <input name="lastName" type="text" id="lastName" class="form-control" placeholder="Last name">
      </div>
    </div>
  </div>
  <div class="form-group">
    <label for="upfile">Profile Picture</label>
    <input name="upfile" type="file" class="form-control" id="upfile">
  </div>
  <div class="form-group">
    <button type="button" id="submit" class="btn btn-outline-primary">Submit</button>
  </div>
</form>
const button = document.querySelector('#submit');

button.addEventListener('click', () => {
  const form = new FormData(document.querySelector('#profileData'));
  const url = './upload.php'
  const request = new Request(url, {
    method: 'POST',
    body: form
  });

  fetch(request)
    .then(response => response.json())
    .then(data => { console.log(data); })
});

But what if we wanna add the file to FormData programmatically, will the script be able to handle the upload?

Answer is yes. There is no change needed in the backend script to accommodate this behavior.

Following code does so:

const uploadButton = document.querySelector('#upload');
uploadButton.addEventListener('click', () => {
  const form = new FormData();
  const file = document.querySelector('#upfile-2').files[0];
  form.append('upfile', file);
  
  const url = './upload.php'
  const request = new Request(url, {
    method: 'POST',
    body: form
  });

  fetch(request)
    .then(response => response.json())
    .then(console.log)
});

HTML for this code will be:

<div>
  <div class="form-group">
    <label for="upfile-2">Profile Picture</label>
    <input type="file" class="form-control" id="upfile-2">
  </div>
  <div class="form-group">
    <button id="upload" class="btn btn-outline-primary">Upload</button>
  </div>
</div>

You can read more about how to work with FormData API, you can read here: https://time2hack.com/2018/06/formdata-api-handle-forms-like-a-boss/


Code

Conclusion

By above methods, you can upload files to PHP backend and keep it backward compatible as well if in case JS is disabled (😒)

Let me know your thoughts and opinions about this article through comments 💬 or on twitter at @patel_pankaj_ and @time2hack.

If you find this article useful, share it with others 🗣