File Uploads in a PHP API: How to Upload Images and PDFs and Validate Them Securely

Illustration of secure image and PDF uploads in a PHP API

Quick answer: In a PHP API, receive the file as multipart/form-data in $_FILES and validate everything before saving: the upload error code, the maximum size, and the real MIME type with finfo, never trusting the type or name sent by the browser. Generate a new random name, save it with move_uploaded_file into a folder that can't run PHP, and return the URL as JSON.

File uploads are common in almost every system: a profile picture, a PDF receipt, a product photo, an attached document, sent from a form, a mobile app or an admin panel.

They also need care. An API that accepts any file without validation is open to malicious files, runaway disk usage, overwritten files, dangerous extensions and security holes. In this article you will build file uploads in a PHP API with multipart/form-data, validating images and PDFs, size and real MIME type, and returning consistent JSON.

In short: never save a file received by the API without checking the upload error, the size, the real content type, a safe name and the destination folder.

How file uploads work in PHP

When a file is sent as multipart/form-data, PHP makes it available in $_FILES. Unlike a JSON API, you don't read it with php://input and json_decode. Extra fields arrive in $_POST:

$_FILES['file']
$_POST['title']

The uploaded file waits in a temporary folder on the server until you move it to its final place with move_uploaded_file. If you don't, PHP deletes it at the end of the request.

Sending a file from an HTML form

<form action="/api/upload" method="post" enctype="multipart/form-data">
    <label>File <input type="file" name="file"></label>
    <label>Title <input type="text" name="title"></label>
    <button type="submit">Upload</button>
</form>

The key part is enctype="multipart/form-data". Without it, the file is not sent.

Sending a file with JavaScript fetch

<input type="file" id="file">
<input type="text" id="title" placeholder="Title">
<button onclick="uploadFile()">Upload</button>

<script>
async function uploadFile() {
    const file = document.getElementById('file').files[0];

    if (!file) {
        alert('Choose a file.');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);
    formData.append('title', document.getElementById('title').value);

    const response = await fetch('/api/upload', { method: 'POST', body: formData });
    const result = await response.json();

    if (!response.ok) {
        alert(result.message || 'Upload failed.');
        return;
    }

    console.log(result.data);
}
</script>

With FormData, don't set the Content-Type header yourself: the browser builds the multipart body and its boundary automatically.

The JSON responses

Even for uploads, the API answers in JSON. On success:

{
  "success": true,
  "message": "File uploaded.",
  "data": {
    "filename": "3f9a1c0e8b7d4e2a9c1b5d6e7f8a9b0c.webp",
    "url": "/uploads/3f9a1c0e8b7d4e2a9c1b5d6e7f8a9b0c.webp"
  }
}

On error:

{
  "success": false,
  "message": "Invalid file.",
  "errors": {
    "file": "This file type is not allowed."
  }
}

Step 1: check that a file arrived

<?php

function jsonResponse(int $statusCode, array $data): void
{
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

if (!isset($_FILES['file']) || is_array($_FILES['file']['error'])) {
    jsonResponse(400, [
        'success' => false,
        'message' => 'No file was sent.',
        'errors' => ['file' => 'Send one file in the "file" field.']
    ]);
}

If the whole request is bigger than post_max_size, PHP throws the body away and $_FILES and $_POST arrive empty, which also lands here. The is_array check rejects file[] with several files when you expect one.

Step 2: check the upload error code

PHP reports problems during the transfer through $_FILES['file']['error']. Turn the codes into clear messages:

<?php

$file = $_FILES['file'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    $messages = [
        UPLOAD_ERR_INI_SIZE   => 'The file is larger than the server allows.',
        UPLOAD_ERR_FORM_SIZE  => 'The file is larger than the form allows.',
        UPLOAD_ERR_PARTIAL    => 'The file was only partially uploaded. Try again.',
        UPLOAD_ERR_NO_FILE    => 'No file was sent.',
        UPLOAD_ERR_NO_TMP_DIR => 'Server configuration error.',
        UPLOAD_ERR_CANT_WRITE => 'Server configuration error.',
        UPLOAD_ERR_EXTENSION  => 'The upload was blocked by the server.',
    ];
    $status = in_array($file['error'], [UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE], true) ? 413 : 400;
    if (in_array($file['error'], [UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION], true)) {
        error_log('Upload error code ' . $file['error']);
        $status = 500;
    }

    jsonResponse($status, [
        'success' => false,
        'message' => $messages[$file['error']] ?? 'Upload failed.'
    ]);
}

Step 3: limit the size

<?php

$maxSize = 5 * 1024 * 1024; // 5 MB

if ($file['size'] > $maxSize) {
    jsonResponse(422, [
        'success' => false,
        'message' => 'File too large.',
        'errors' => ['file' => 'The file must be 5 MB or smaller.']
    ]);
}
Watch out: PHP has its own limits in php.ini (upload_max_filesize and post_max_size), and so does the web server (client_max_body_size on Nginx). Your code's limit only works if it is lower than all of them.

Step 4: check the real content type

The name and the type sent by the browser are just text the client chose: anyone can rename shell.php to photo.jpg. Read the file's real type with finfo, and take the extension from that type instead of from the original name:

<?php

$allowed = [
    'image/jpeg'      => 'jpg',
    'image/png'       => 'png',
    'image/webp'      => 'webp',
    'application/pdf' => 'pdf',
];

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file['tmp_name']);

if (!isset($allowed[$mimeType])) {
    jsonResponse(422, [
        'success' => false,
        'message' => 'Invalid file.',
        'errors' => ['file' => 'Upload only JPG, PNG, WEBP or PDF files.']
    ]);
}

$extension = $allowed[$mimeType]; // never from the name the user sent

For images, you can go one step further: getimagesize() confirms the file decodes as an image, and re-encoding it (with GD or Imagick) drops anything hidden inside it, along with metadata such as GPS location.

Step 5: generate a safe name

Never save a file under the name the user sent. It may contain spaces, odd characters or path tricks like ../, and two users can send photo.jpg at the same time:

<?php

$newName = bin2hex(random_bytes(16)) . '.' . $extension;

A random name also stops anyone from guessing the URLs of other people's files.

Step 6: move the file to its final folder

<?php

$uploadDir = __DIR__ . '/uploads';

if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
    error_log('Could not create the upload folder.');
    jsonResponse(500, ['success' => false, 'message' => 'Internal server error.']);
}

if (!move_uploaded_file($file['tmp_name'], $uploadDir . '/' . $newName)) {
    error_log('move_uploaded_file failed for ' . $newName);
    jsonResponse(500, ['success' => false, 'message' => 'Could not save the file.']);
}

On Linux, the folder must be writable by the web server user (www-data, apache or nginx). move_uploaded_file only accepts files that really came from an upload, which protects you from tricks that point tmp_name at other files on the server.

Complete upload endpoint

<?php

header('Content-Type: application/json; charset=utf-8');

function jsonResponse(int $statusCode, array $data): void
{
    http_response_code($statusCode);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Allow: POST');
    jsonResponse(405, ['success' => false, 'message' => 'Use POST.']);
}

try {
    if (!isset($_FILES['file']) || is_array($_FILES['file']['error'])) {
        jsonResponse(400, ['success' => false, 'message' => 'Send one file in the "file" field.']);
    }

    $file = $_FILES['file'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $tooBig = in_array($file['error'], [UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE], true);
        jsonResponse($tooBig ? 413 : 400, [
            'success' => false,
            'message' => $tooBig ? 'The file is too large.' : 'Upload failed. Try again.'
        ]);
    }

    if ($file['size'] > 5 * 1024 * 1024) {
        jsonResponse(422, [
            'success' => false,
            'message' => 'File too large.',
            'errors' => ['file' => 'The file must be 5 MB or smaller.']
        ]);
    }

    $allowed = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        'application/pdf' => 'pdf',
    ];

    $mimeType = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);

    if (!isset($allowed[$mimeType])) {
        jsonResponse(422, [
            'success' => false,
            'message' => 'Invalid file.',
            'errors' => ['file' => 'Upload only JPG, PNG, WEBP or PDF files.']
        ]);
    }

    $uploadDir = __DIR__ . '/uploads';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $newName = bin2hex(random_bytes(16)) . '.' . $allowed[$mimeType];

    if (!move_uploaded_file($file['tmp_name'], $uploadDir . '/' . $newName)) {
        throw new RuntimeException('move_uploaded_file failed');
    }

    jsonResponse(201, [
        'success' => true,
        'message' => 'File uploaded.',
        'data' => [
            'filename' => $newName,
            'original_name' => mb_substr(basename($file['name']), 0, 255),
            'mime_type' => $mimeType,
            'size' => $file['size'],
            'url' => '/uploads/' . $newName
        ]
    ]);

} catch (Throwable $e) {
    error_log('Upload error: ' . $e->getMessage());
    jsonResponse(500, ['success' => false, 'message' => 'Internal server error.']);
}

Saving the file details in the database

CREATE TABLE files (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NULL,
    title VARCHAR(150) NULL,
    original_name VARCHAR(255) NOT NULL,
    stored_name VARCHAR(64) NOT NULL,
    mime_type VARCHAR(100) NOT NULL,
    size BIGINT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
<?php

$stmt = $pdo->prepare("
    INSERT INTO files (user_id, title, original_name, stored_name, mime_type, size)
    VALUES (:user_id, :title, :original_name, :stored_name, :mime_type, :size)
");

$stmt->execute([
    ':user_id' => $user['sub'] ?? null,
    ':title' => isset($_POST['title']) ? mb_substr(trim($_POST['title']), 0, 150) : null,
    ':original_name' => mb_substr(basename($file['name']), 0, 255),
    ':stored_name' => $newName,
    ':mime_type' => $mimeType,
    ':size' => $file['size'],
]);

This lets you list uploads later, link attachments to users or orders, and delete files cleanly. When you show original_name in HTML, escape it: it is still user input.

Protect the endpoint with authentication

If uploads belong to a logged-in area, validate the token before accepting any file, so strangers can't fill your disk. See JWT authentication in PHP. For private documents (invoices, IDs), store them outside the public web root and serve them through a PHP endpoint that checks who is asking.

Block PHP execution in the upload folder (Apache)

If the upload folder is public, make sure nothing in it can run as PHP. Put this .htaccess inside uploads/:

# Never run scripts from this folder
<FilesMatch "\.(php|phtml|phar|php[0-9]?)$">
    Require all denied
</FilesMatch>

# Only needed with mod_php; on PHP-FPM this directive would cause a 500 error
<IfModule mod_php.c>
    php_flag engine off
</IfModule>

Options -Indexes

The <IfModule> wrapper matters: many servers run PHP-FPM, where php_flag is not allowed and breaks the whole folder with a 500 error. On Nginx, add a location ^~ /uploads/ block that doesn't pass .php files to PHP-FPM.

php.ini settings

file_uploads = On
upload_max_filesize = 5M
post_max_size = 8M
max_file_uploads = 20

post_max_size must be larger than upload_max_filesize, because it covers the whole request including other fields.

Should I convert images to WebP?

For websites, converting uploads to WebP and resizing them usually cuts file sizes a lot and speeds up pages. Get validation, safe names and storage right first; then add resizing and conversion as a second step.

Common upload mistakes in PHP

1. Forgetting multipart/form-data

Without enctype="multipart/form-data", the file is not sent.

2. Trusting the extension or the browser's type

Both are chosen by the client. Check the real content with finfo and take the extension from it.

3. Saving under the original name

It causes overwrites and odd characters, and can reveal personal data.

4. No size limit

Without one, large files fill the disk quickly.

5. Exposing internal server paths

Never return paths like /var/www/site/uploads/file.pdf. Return only a public URL or an ID.

Checklist for secure uploads in a PHP API

  • Does the endpoint accept only POST?
  • Is the upload error code checked?
  • Is there a maximum size, below the php.ini and web server limits?
  • Is the real MIME type checked against an allowlist?
  • Does the extension come from the real type, not the name?
  • Is the stored name random and unique?
  • Does the folder exist, with the right permissions?
  • Is PHP execution blocked in the upload folder?
  • Does the API return JSON for success and errors?
  • Do sensitive uploads require authentication?

Conclusion

File uploads in a plain PHP API are simple to build but need care. The core rule is to never trust the file the user sent: check the upload, limit the size, read the real type, generate a safe name, move the file properly and answer with consistent JSON.

With this structure, your API can safely receive images, PDFs and attachments from admin panels, websites, mobile apps and integrations. For validating the other fields of the request, see input validation in a plain PHP API.

Frequently asked questions about file uploads in PHP APIs

How do I send a file to a PHP API?

Send it as multipart/form-data. In PHP, the file arrives in $_FILES.

Can I send a file together with JSON?

The practical way is FormData: the file goes to $_FILES and the other fields to $_POST. Pure JSON would require Base64, which makes the request about a third larger.

Is checking the file extension enough?

No. The extension is trivial to change. Check the real type with finfo.

What maximum size should I allow?

It depends on the system. For regular images, 2 to 5 MB is usually enough; adjust for PDFs as needed.

Should I keep the original file name?

No. Store the file under a random name and, if you need the original, save it in the database.

Where should uploaded files go?

In an upload folder that can't run scripts, outside the web root for private files, or in an external storage service. In every case, validate before saving.

More in PHP