Advanced AJAX

AJAX File Uploads with FormData and PHP

Upload files asynchronously with FormData and validate file content safely in PHP.

AJAX File Uploads with FormData and PHP

The browser can upload files without a full page reload by sending a FormData object. The server must treat every uploaded file as untrusted.

Browser upload

const formData = new FormData();
formData.append('document', fileInput.files[0]);
const response = await fetch('/api/upload.php', {
  method: 'POST',
  body: formData
});

Do not manually set the multipart Content-Type; the browser adds the required boundary.

PHP validation

Check the upload error code, enforce a strict size limit, inspect content with Fileinfo, and allow only required MIME types. Generate a random server-side filename and store files outside the public web root where possible.

Never trust the original filename or browser-provided MIME type. Add authentication, authorization, CSRF protection, malware scanning where appropriate, and safe download handling.

Share this page Help other developers discover this resource.