Home / Guides / WordPress handbook / Chapter 04

WordPress handbook · Chapter 04 · Security

File Upload Security

Accepting a file from the internet means letting a stranger put bytes on your server. If any layer misjudges those bytes, the result can be remote code execution, malware distribution, cross-site scripting, a denial of service, or a leak of other people's private documents. This chapter explains each layer of defence, why each is needed, and how they fit together into a safe workflow.

Updated · 37 min read · Level: Advanced

On this page
  1. Why uploads are a high-risk feature
  2. Upload contexts on a WordPress site
  3. How WordPress handles uploads natively
  4. Validation: extension, MIME type and content
  5. Filenames and path traversal
  6. Size limits, timeouts and rate limits
  7. Storage: permissions, non-executable directories and the web root
  8. Access control: authentication, authorization, ownership and CSRF
  9. Delivering files: authenticated downloads and temporary links
  10. Malware scanning and quarantine
  11. Retention, privacy and CSRF on upload forms
  12. Reference architecture: a secure upload workflow in PHP
  13. PHP upload error codes
  14. Upload troubleshooting database
  15. Upload security checklist

Why uploads are a high-risk feature

An attacker who can upload a file is usually after one of these:

GoalHow it is attemptedDefence that stops it
Execute code on the serverUpload shell.php, shell.phtml, shell.php.jpg, or a .htaccess that makes images executable, then request it by URL.Extension allowlist, content validation, random filenames, no PHP execution in upload directories, storage outside the web root
Attack other users' browsers (stored XSS)Upload an SVG or HTML file containing script, served from your domain so it runs with your cookies' origin.Disallow SVG/HTML from untrusted users, or sanitise them; Content-Disposition: attachment; X-Content-Type-Options: nosniff; serve user content from a separate domain
Overwrite or read other filesFilenames such as ../../wp-config.php, or archives with traversal paths inside ("zip slip").Never use client filenames for storage paths; normalise and verify paths; safe archive extraction (or none)
Exhaust resourcesHuge files, thousands of uploads, decompression bombs, images with enormous pixel dimensions.Size limits at every layer, rate limits, pixel-dimension limits, quotas
Exploit file parsersMalformed images, PDFs or office documents aimed at bugs in ImageMagick, GD, PDF libraries or antivirus engines.Patched libraries, minimal processing of untrusted files, isolation, re-encoding
Host malware or phishingUse your domain's reputation to distribute malicious files or HTML phishing pages.Scanning, quarantine, attachment downloads, restricting who can upload
Steal other people's documentsGuess or enumerate predictable URLs (/uploads/2026/12/passport-john-smith.pdf), or change an ID in a download link (insecure direct object reference, IDOR).Private storage, authenticated downloads, ownership checks, random identifiers
The one rule that matters most

No single check is enough. Extension checks are bypassed with tricky names, MIME checks with forged headers, and content checks with polyglot files that are valid in two formats at once. The goal is layers. Even if validation is fooled, the file must land somewhere it cannot execute, under a name the attacker does not control, served in a way that stops the browser treating it as a web page.

Upload contexts on a WordPress site

Different features accept files from people with very different levels of trust. Write down every upload path on the site, because forms and plugins add paths that are easy to forget.

ContextWho uploadsTypical storageMain risksKey controls
Media LibraryUsers with upload_files (Author and above)uploads/YYYY/MM/, publicCompromised author account uploading malicious files; SVG XSS if SVG is enabledCore MIME allowlist, least privilege, no unfiltered_upload, SVG sanitisation
Contact form uploadsAnonymous visitorsPlugin folder under uploads, often with a random subfolder; sometimes attached to email and deletedMalware, spam storage, public exposure of personal documentsStrict type and size limits, CAPTCHA/rate limits, no public listing, email-and-delete or private storage, retention
User profile uploads (avatars)Registered users, often low trustPublic uploadsImage parser attacks, inappropriate content, storage abuseImages only, re-encode, dimension limits, moderation
Membership / course uploadsMembers, studentsPlugin-defined, mixed public/privateMembers reading each other's submissions (IDOR)Ownership checks, private storage, authenticated downloads
Ecommerce uploads (custom product files, artwork)CustomersOrder-linked, often under uploadsLarge files, malware, privacySize and type limits, link to order and customer, retention after fulfilment
Downloadable productsShop staff upload, customers downloaduploads/woocommerce_uploads/ with deny rulesDirect URL access bypassing purchase checksServer deny rules (WooCommerce writes them for Apache; Nginx needs manual rules), forced or X-Accel/X-Sendfile download methods
Support ticket uploadsCustomers, sometimes anonymousHelpdesk plugin storageScreenshots containing credentials or personal data; malware sent to staffPrivate storage, scanning, staff-only access, retention
Job applicationsAnonymous applicantsForm or recruitment plugin storageCVs with personal data publicly reachable; macro-enabled documentsPDF/DOCX only, private storage, strict retention, access limited to recruiters
Public upload endpoints (REST/AJAX)Anyone who finds the endpointVariesUnauthenticated arbitrary file upload: the classic critical plugin vulnerabilityAuthentication, capability checks, rate limits, WAF rules, and removing endpoints that are not needed
Private document portalsClients, staffShould be outside the web root or private object storageData breachEverything in this chapter
Third-party integrationsUsers via an external service (cloud drive pickers, form SaaS)External storageOver-broad OAuth scopes, leaked tokens, files shared publicly by defaultMinimal scopes, private sharing defaults, token rotation

How WordPress handles uploads natively

Core's Media Library path (wp_handle_upload() → media_handle_upload()) already does several things right, and custom upload code should reuse them rather than reinvent them:

  • Capability check: the user must have upload_files.
  • Allowlist: only extensions/MIME types returned by get_allowed_mime_types() are accepted. Plugins extend it with the upload_mimes filter. Users with unfiltered_upload (by default nobody on Multisite and, on single sites, only when ALLOW_UNFILTERED_UPLOADS is defined) bypass it.
  • Content check: wp_check_filetype_and_ext() compares the extension with the file's real content for images (and, using fileinfo, for several other types). A .jpg that is really a PNG is renamed; a file whose content contradicts its claimed type can be rejected.
  • Filename sanitising: sanitize_file_name() removes special characters. It also turns extra dots in names such as file.php.jpg into underscores when the inner extension is not allowed. Name collisions get a numeric suffix.
  • Image processing: GD or Imagick generate sub-sizes. Images above the "big image" threshold (2560 px by default, filterable via big_image_size_threshold) are scaled and the original kept. Recent releases can also do some of this processing in the browser before upload; check which method your version and settings use when diagnosing image problems.
What core does not do

Core does not scan for malware, does not make uploads private (every file in uploads has a public URL), does not rate-limit, and does not stop PHP from executing in uploads. That last point is the web server's job. Never define ALLOW_UNFILTERED_UPLOADS on a production site to "fix" an unsupported file type; add only the specific type you need through upload_mimes.

<?php
// Allow .gpx route files for users who can already upload media.
add_filter( 'upload_mimes', function ( $mimes ) {
	$mimes['gpx'] = 'application/gpx+xml';
	return $mimes;
} );
// Note: if the server's fileinfo reports a different MIME (often text/xml for GPX),
// wp_check_filetype_and_ext() may still reject it. Check what finfo returns for a real
// sample before adjusting, and never widen the check to "any type".

Validation: extension, MIME type and content

Why trusting the browser's extension (or MIME type) is insufficient

Everything in a multipart upload request is controlled by the sender: the filename, the declared Content-Type, and the bytes. A browser fills these in honestly, but an attacker does not use a browser. They send a raw HTTP request with any values they like. So:

  • $_FILES['x']['name'] is a claim. It can say invoice.pdf while the content is PHP.
  • $_FILES['x']['type'] is a claim. It can say image/jpeg for anything.
  • The HTML accept=".pdf" attribute and JavaScript checks are conveniences for honest users. They are never security controls.
  • What decides how a file is treated later is often the extension (web servers map extensions to handlers), while what it is depends on the bytes. Safety requires that the stored extension is chosen by you and matches validated content.

The validation layers

  1. Extension allowlist. Take the final extension, lower-cased, and accept only a short explicit list. Allowlists fail safe; denylists ("block .php") always miss something: .phtml, .php5, .phar, .pht, .shtml, .htaccess, .svg, .html, and case variants like .PhP.
  2. Server-side MIME detection. Use PHP's fileinfo (finfo), which inspects the file's magic bytes, and require the result to match the type expected for that extension.
  3. Format-specific validation. For images, getimagesize() must parse dimensions within limits. For PDFs, the header must start with %PDF-. Stronger still is to re-encode images (load and save through GD or Imagick), which discards appended payloads and metadata. Note that re-encoding also runs the image parser on untrusted input, so libraries must be patched.
  4. Size limits on the actual file on disk, not on a client-declared length.
  5. Malware scanning for document types that can carry active content (PDF, Office files, archives).
Deep dive: double extensions, polyglots and malformed files

Double extensions. Apache's AddHandler directive maps an extension to a handler wherever it appears in the filename, so on servers configured with AddHandler application/x-httpd-php .php, a file named photo.php.jpg may execute as PHP. Modern distributions use <FilesMatch "\.php$"> with SetHandler, which only matches the final extension, but legacy and hand-tuned servers still exist. The defence is random stored filenames with a single, validated extension, plus no PHP handler in upload directories.

Trailing characters. Historic tricks include null bytes (shell.php%00.jpg, fixed in PHP long ago), trailing dots or spaces (meaningful on Windows filesystems), and Unicode look-alike characters. Generating your own filename makes all of these irrelevant.

Polyglots. A file can be a valid GIF and also contain PHP or JavaScript, because the image format tolerates trailing or comment data. It passes getimagesize() and finfo. If it lands in a directory where PHP executes, or is served as HTML, the payload runs. Re-encoding destroys most polyglots, and non-executable storage makes the rest harmless.

Malformed and oversized files. A 50 KB PNG can declare 100,000 × 100,000 pixels and exhaust memory when decoded ("decompression bomb"). Check dimensions before any processing; WordPress's big-image scaling does not protect against images too large to open in the first place. ZIP archives can expand a few KB into many GB: never extract untrusted archives unless you limit total expanded size, entry count and paths.

SVG. SVG is XML and can contain <script>, event handlers and external references. Core does not allow SVG uploads. If you enable it, restrict it to trusted roles and sanitise with a maintained SVG sanitiser, or serve SVGs only as <img> sources from a separate domain.

Filenames and path traversal

Safe filenames contain only characters you chose and cannot alter the directory they are written to. Random filenames go further: the stored name is a random token (for example 32 hex characters from random_bytes(16)) plus the validated extension. This:

  • removes any attacker control over the name (no double extensions, no .htaccess, no traversal),
  • makes URLs unguessable, which helps privacy, although it is not access control,
  • prevents collisions and overwrites,
  • separates display name from storage name: keep the sanitised original name in the database for display and download headers only.

Path traversal means using ../ sequences (or encoded forms such as %2e%2e%2f, or absolute paths) to escape the intended directory. Never build a filesystem path from user input. If a path must include an identifier, validate it against a strict pattern (^[a-f0-9]{32}\.(pdf|png)$), build the full path, resolve it with realpath(), and confirm it still starts with the storage directory. Apply the same rule to download handlers, which are the more common place for traversal bugs (download.php?file=../../wp-config.php).

Size limits, timeouts and rate limits

Every layer in the request path enforces its own maximum body size, and the smallest one wins. When an upload fails because it is too big, the error comes from whichever layer refused it, which is why the same problem shows up as several different errors:

LayerSettingDefault / typicalFailure looks like
CDN / WAFPlan limitOften 100 MB on entry plans413 from the CDN, or a CDN-branded error
Nginxclient_max_body_size1 MB if unset413 Request Entity Too Large (Nginx page)
ApacheLimitRequestBody1 GB in recent 2.4 releases; hosts often set lower413
ModSecuritySecRequestBodyLimitHost-defined413 or 403
PHPpost_max_size8MEmpty $_POST and $_FILES; WordPress may show "link you followed has expired" (the nonce was lost)
PHPupload_max_filesize2MUPLOAD_ERR_INI_SIZE (1); "exceeds the maximum upload size"
PHPmax_file_uploads20Extra files silently dropped
PHP / web servermax_input_time, max_execution_time, proxy timeouts60 s / 30 s / 60 sTimeouts on slow connections or heavy image processing
ApplicationYour own limitShould be the smallestA clear, friendly error

Set your application limit below every infrastructure limit so users get a helpful message instead of a raw server error. post_max_size must be larger than upload_max_filesize, since the request includes other fields and multipart overhead.

Rate limits protect storage and processing: per user (for example 10 uploads per hour), per IP for anonymous forms, and total quota per user. Enforce them at the WAF for anonymous endpoints, and in the application for per-account limits.

Storage: permissions, non-executable directories and the web root

Upload directory permissions

uploads must be writable by the PHP user, typically 755 directories and 644 files owned by the site user. Never 777. Writability is unavoidable, which is exactly why execution must be prevented there.

Executable file prevention

Configure the web server so that nothing in wp-content/uploads/ is ever passed to PHP, even if a .php file gets there. On Apache this is a .htaccess in the uploads folder (or a <Directory> block in the server config, which an uploaded .htaccess cannot override). On Nginx it is a location block that must appear before the general PHP block. Chapter 07 has tested configurations for both. Verify by placing a harmless test file and requesting it:

echo '<?php echo "EXECUTED";' > wp-content/uploads/ff-exec-test.php
curl -s -o /dev/null -w "%{http_code}\n" https://example.com/wp-content/uploads/ff-exec-test.php
# Expect 403 (or 404). If the body says EXECUTED, PHP runs in uploads: fix before anything else.
rm wp-content/uploads/ff-exec-test.php

Storage outside the public web root

For private documents, the strongest design is to store files outside the document root, for example /home/account/private-uploads/ when the site is served from /home/account/public_html/. The web server has no URL mapped to that directory, so the files cannot be requested directly whatever their names, permissions or server rules. They are served only through PHP code that checks authentication and authorisation first. On hosts where you cannot write outside the web root, use a directory with a server-level deny-all rule, or private object storage (S3-compatible buckets with public access blocked, served through short-lived signed URLs).

For a high-volume public user-content site, consider serving uploads from a separate domain (usercontent.example.net) so that any HTML or SVG that slips through cannot run script in your main site's origin.

Access control: authentication, authorization, ownership and CSRF

A secure upload or download handler answers four separate questions, in order:

  1. Who is this? (Authentication.) is_user_logged_in(), or a valid signed token for anonymous flows.
  2. Did they mean to do this? (CSRF protection.) A nonce from wp_nonce_field(), checked with check_admin_referer() or wp_verify_nonce().
  3. Are they allowed to do this kind of thing? (Authorization.) current_user_can( 'capability' ).
  4. Are they allowed to do it to this object? (Ownership.) Is the document's owner the current user, or does the user hold a staff capability that covers all documents?
Why a WordPress nonce does not replace authorization checks

A nonce answers question 2 only. It is generated for any logged-in user who can load the page containing the form or link, and it stays valid for up to 24 hours. Picture a download link built as ?action=download&doc=123&_wpnonce=abc where the nonce action is just "download". A subscriber who receives a valid nonce for their own document 123 can change doc=123 to doc=124 and download someone else's file, because the nonce is still valid. Without an ownership check, that is an IDOR vulnerability, and this exact pattern appears again and again in published plugin vulnerabilities. Always pair nonces with capability and ownership checks. Binding the nonce action to the object ID ('ff_download_' . $doc_id) narrows the damage but is still not authorization.

For anonymous forms (job applications, contact uploads), there is no user to authorize. Protection comes from rate limits, CAPTCHA, strict validation, private storage, and making sure the download side is restricted to staff.

Malware scanning and quarantine

Scanning catches known-malicious files (infected documents, web shells, malware droppers) before staff open them or the site serves them. Options include ClamAV run by the host or on the server, the host's own scanning service (Imunify and similar), or a commercial scanning API. Scanners find known threats; they do not replace the other layers.

Quarantine workflow

  1. Store new uploads in a quarantine area (private, non-executable) with status pending.
  2. Scan asynchronously (a background job or Action Scheduler task), because scans can be slow and should not hold the upload request open.
  3. On a clean result, mark the file available (move it to the main private store if you separate them). On an infected result, mark it rejected, keep it quarantined for investigation for a short defined period, notify an administrator, and never serve it.
  4. On scanner errors or timeouts, fail closed: leave the file pending and alert someone. Never assume a file is clean because scanning failed.
  5. Rescan periodically if files are kept long-term, since signatures improve over time.

False positives happen, especially with macro-enabled office documents and some PDFs. Provide an administrator path to review and release a file, logging who released it and why.

Retention, privacy and CSRF on upload forms

Uploaded documents are often the most sensitive personal data a site holds: identity documents, CVs, medical forms, signed contracts. Data protection laws such as the GDPR and South Africa's POPIA expect you to collect only what you need, keep it only as long as necessary, protect it appropriately, and be able to find and delete it on request.

  • Define a retention period per upload type (for example 6 months for unsuccessful job applications), and enforce it with a scheduled clean-up job that deletes both the file and its database record.
  • Prefer "email and delete" for simple contact-form attachments, if the mailbox is the system of record and the email channel is acceptable for the data.
  • Strip metadata from public images (EXIF can contain GPS coordinates). Re-encoding usually does this.
  • Include uploads in privacy tooling: WordPress's personal data export and erase tools only cover data that plugins register with them.
  • Backups contain uploads too. Deleted files persist in backups until those backups expire; reflect that in your retention statement.

CSRF on upload forms: an attacker's page can make a logged-in user's browser submit a form to your site. Without a nonce, that could upload attacker-chosen files into the victim's account, or delete their documents through a delete action. Every state-changing upload, delete or replace action needs a nonce, checked server-side.

Reference architecture: a secure upload workflow in PHP

The code below is an educational reference for a private document upload feature built on WordPress APIs. It shows the order and placement of every control discussed above. Adapt and review it for your project before production use. It assumes PHP 7.4+ and a private storage directory defined in wp-config.php:

// Absolute path OUTSIDE the document root, writable by the PHP user, not web-accessible.
define( 'FF_PRIVATE_DIR', '/home/example/private-uploads' );

Flow

  1. Logged-in user submits the form to admin-post.php (no nopriv hook, so anonymous requests never reach the handler).
  2. Handler checks: login → nonce (CSRF) → capability → rate limit → PHP upload error → is_uploaded_file → real size → extension allowlist + wp_check_filetype_and_ext() → independent finfo detection → format-specific checks → scanner hook.
  3. File moved to private storage under a random name; ownership and metadata recorded on a private custom post type.
  4. Downloads go through a handler that checks login → nonce bound to the document → existence → ownership or staff capability, then streams with safe headers.
  5. Optional signed expiring links for login-free access.
<?php
/**
 * Plugin Name: FF Private Documents (reference architecture)
 * Description: Authenticated, validated, private file upload and download workflow.
 */
defined( 'ABSPATH' ) || exit;

final class FF_Private_Docs {

	const MAX_BYTES  = 10485760;            // 10 MB: keep below PHP and server limits.
	const RATE_LIMIT = 10;                  // Uploads per user per hour.
	const MAX_PIXELS = 40000000;            // Reject images over 40 megapixels (decompression bombs).
	const UPLOAD_CAP = 'read';              // Minimum capability. Prefer a dedicated custom capability.
	const STAFF_CAP  = 'ff_view_all_documents';
	const ALLOWED    = array(               // Allowlist: extension => the ONLY acceptable real MIME type.
		'pdf'  => 'application/pdf',
		'jpg'  => 'image/jpeg',
		'jpeg' => 'image/jpeg',
		'png'  => 'image/png',
	);

	public static function init() {
		add_action( 'init', array( __CLASS__, 'register_type' ) );
		add_action( 'admin_post_ff_upload', array( __CLASS__, 'handle_upload' ) );
		add_action( 'admin_post_ff_download', array( __CLASS__, 'handle_download' ) );
		// Signed links work with or without a login session.
		add_action( 'admin_post_ff_signed', array( __CLASS__, 'handle_signed' ) );
		add_action( 'admin_post_nopriv_ff_signed', array( __CLASS__, 'handle_signed' ) );
	}

	public static function register_type() {
		register_post_type( 'ff_document', array(
			'public'             => false,
			'publicly_queryable' => false,
			'show_ui'            => false,
			'show_in_rest'       => false,
			'rewrite'            => false,
			'query_var'          => false,
			'supports'           => array( 'title', 'author' ),
		) );
	}

	/** Redirect back with a short error code; details go to the server log only. */
	private static function fail( $code ) {
		$back = wp_get_referer() ? wp_get_referer() : home_url( '/' );
		wp_safe_redirect( add_query_arg( 'ff_error', rawurlencode( $code ), $back ) );
		exit;
	}

	private static function storage_dir() {
		if ( ! defined( 'FF_PRIVATE_DIR' ) ) {
			return new WP_Error( 'ff_config', 'FF_PRIVATE_DIR is not defined.' );
		}
		$dir = rtrim( FF_PRIVATE_DIR, '/\\' );
		if ( ! wp_mkdir_p( $dir ) || ! is_writable( $dir ) ) {
			return new WP_Error( 'ff_storage', 'Private storage directory is missing or not writable.' );
		}
		return $dir;
	}

	public static function handle_upload() {
		// 1. Authentication (admin-post.php already requires login for this hook; be explicit).
		if ( ! is_user_logged_in() ) {
			self::fail( 'auth' );
		}
		// 2. CSRF: proves the request came from our form for this user. Dies with 403 if invalid.
		check_admin_referer( 'ff_upload', 'ff_nonce' );

		// 3. Authorization: a valid nonce does NOT mean the user may upload.
		if ( ! current_user_can( self::UPLOAD_CAP ) ) {
			self::fail( 'forbidden' );
		}
		$user_id = get_current_user_id();

		// 4. Per-user rate limit (approximate window; use a counter table for strict limits).
		$rl_key = 'ff_up_' . $user_id;
		$count  = (int) get_transient( $rl_key );
		if ( $count >= self::RATE_LIMIT ) {
			self::fail( 'rate' );
		}

		// 5. Structural checks. Reject arrays (multiple files) we did not ask for.
		if ( empty( $_FILES['ff_file'] ) || ! is_array( $_FILES['ff_file'] ) || is_array( $_FILES['ff_file']['name'] ) ) {
			self::fail( 'nofile' );
		}
		$file = $_FILES['ff_file'];
		if ( UPLOAD_ERR_OK !== (int) $file['error'] ) {
			error_log( sprintf( 'ff_upload: PHP upload error %d (user %d)', (int) $file['error'], $user_id ) );
			self::fail( 'php_' . (int) $file['error'] );
		}
		if ( ! is_uploaded_file( $file['tmp_name'] ) ) {
			self::fail( 'invalid' );
		}

		// 6. Size of the real file on disk (the client-declared size is not trusted).
		$size = filesize( $file['tmp_name'] );
		if ( false === $size || $size < 1 || $size > self::MAX_BYTES ) {
			self::fail( 'size' );
		}

		// 7. Extension + content checks. $file['type'] comes from the client and is ignored.
		$check = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], self::ALLOWED );
		$ext   = $check['ext'] ? strtolower( $check['ext'] ) : '';
		if ( '' === $ext || ! isset( self::ALLOWED[ $ext ] ) ) {
			self::fail( 'type' );
		}
		$finfo    = new finfo( FILEINFO_MIME_TYPE );
		$detected = $finfo->file( $file['tmp_name'] );
		if ( self::ALLOWED[ $ext ] !== $detected ) {
			self::fail( 'type' );
		}

		// 8. Format-specific sanity checks.
		if ( 'application/pdf' === $detected ) {
			$fh   = fopen( $file['tmp_name'], 'rb' );
			$head = $fh ? fread( $fh, 5 ) : '';
			if ( $fh ) {
				fclose( $fh );
			}
			if ( '%PDF-' !== $head ) {
				self::fail( 'type' );
			}
		} else {
			$img = @getimagesize( $file['tmp_name'] );
			if ( ! $img || $img[0] < 1 || $img[1] < 1 || ( $img[0] * $img[1] ) > self::MAX_PIXELS ) {
				self::fail( 'type' );
			}
		}

		// 9. Malware scan hook. Return true only for a confirmed clean result; fail closed otherwise.
		$verdict = apply_filters( 'ff_scan_upload', null, $file['tmp_name'], $detected );
		if ( true !== $verdict ) {
			error_log( sprintf( 'ff_upload: scan did not return clean (user %d)', $user_id ) );
			self::fail( 'scan' );
		}

		// 10. Store outside the web root under a random name with the validated extension.
		$dir = self::storage_dir();
		if ( is_wp_error( $dir ) ) {
			error_log( 'ff_upload: ' . $dir->get_error_message() );
			self::fail( 'storage' );
		}
		$stored = bin2hex( random_bytes( 16 ) ) . '.' . $ext;
		$dest   = $dir . DIRECTORY_SEPARATOR . $stored;
		if ( ! move_uploaded_file( $file['tmp_name'], $dest ) ) {
			error_log( sprintf( 'ff_upload: move_uploaded_file failed (user %d)', $user_id ) );
			self::fail( 'storage' );
		}
		@chmod( $dest, 0640 );

		// 11. Record ownership. The original name is stored for display only, never for paths.
		$doc_id = wp_insert_post( array(
			'post_type'   => 'ff_document',
			'post_status' => 'private',
			'post_author' => $user_id,
			'post_title'  => sanitize_file_name( wp_basename( $file['name'] ) ),
		), true );
		if ( is_wp_error( $doc_id ) ) {
			wp_delete_file( $dest );    // Do not leave orphaned files behind.
			self::fail( 'db' );
		}
		update_post_meta( $doc_id, '_ff_stored', $stored );
		update_post_meta( $doc_id, '_ff_mime', $detected );
		update_post_meta( $doc_id, '_ff_size', $size );
		update_post_meta( $doc_id, '_ff_sha256', hash_file( 'sha256', $dest ) );

		set_transient( $rl_key, $count + 1, HOUR_IN_SECONDS );

		$back = wp_get_referer() ? wp_get_referer() : home_url( '/' );
		wp_safe_redirect( add_query_arg( 'ff_uploaded', '1', $back ) );
		exit;
	}

	public static function handle_download() {
		if ( ! is_user_logged_in() ) {
			auth_redirect();                                   // Sends to login, then back.
		}
		$doc_id = isset( $_GET['doc'] ) ? absint( $_GET['doc'] ) : 0;
		check_admin_referer( 'ff_download_' . $doc_id );       // Nonce bound to this document.

		$doc = get_post( $doc_id );
		if ( ! $doc || 'ff_document' !== $doc->post_type ) {
			wp_die( esc_html__( 'File not found.' ), '', array( 'response' => 404 ) );
		}
		// Ownership: the owner, or staff with an explicit capability. Answer 404 rather
		// than 403 so the existence of other people's documents is not revealed.
		$is_owner = ( (int) $doc->post_author === get_current_user_id() );
		if ( ! $is_owner && ! current_user_can( self::STAFF_CAP ) ) {
			wp_die( esc_html__( 'File not found.' ), '', array( 'response' => 404 ) );
		}
		self::stream( $doc );
	}

	/** Build a signed link that expires after $ttl seconds (bearer token: keep it short). */
	public static function signed_url( $doc_id, $ttl = 900 ) {
		$doc_id  = absint( $doc_id );
		$expires = time() + absint( $ttl );
		$sig     = hash_hmac( 'sha256', $doc_id . '|' . $expires, wp_salt( 'auth' ) );
		return add_query_arg(
			array( 'action' => 'ff_signed', 'doc' => $doc_id, 'exp' => $expires, 'sig' => $sig ),
			admin_url( 'admin-post.php' )
		);
	}

	public static function handle_signed() {
		$doc_id  = isset( $_GET['doc'] ) ? absint( $_GET['doc'] ) : 0;
		$expires = isset( $_GET['exp'] ) ? absint( $_GET['exp'] ) : 0;
		$sig     = isset( $_GET['sig'] ) ? sanitize_text_field( wp_unslash( $_GET['sig'] ) ) : '';
		$expect  = hash_hmac( 'sha256', $doc_id . '|' . $expires, wp_salt( 'auth' ) );
		if ( $expires < time() || ! hash_equals( $expect, $sig ) ) {
			wp_die( esc_html__( 'This download link is invalid or has expired.' ), '', array( 'response' => 403 ) );
		}
		$doc = get_post( $doc_id );
		if ( ! $doc || 'ff_document' !== $doc->post_type ) {
			wp_die( esc_html__( 'File not found.' ), '', array( 'response' => 404 ) );
		}
		self::stream( $doc );
	}

	private static function stream( WP_Post $doc ) {
		$dir    = self::storage_dir();
		$stored = (string) get_post_meta( $doc->ID, '_ff_stored', true );
		// Defence in depth: the stored name was generated by us, but verify its shape anyway.
		if ( is_wp_error( $dir ) || ! preg_match( '/^[a-f0-9]{32}\.(pdf|jpe?g|png)$/', $stored ) ) {
			wp_die( esc_html__( 'File unavailable.' ), '', array( 'response' => 404 ) );
		}
		$path = realpath( $dir . DIRECTORY_SEPARATOR . $stored );
		$base = realpath( $dir );
		if ( ! $path || ! $base || 0 !== strpos( $path, $base . DIRECTORY_SEPARATOR ) || ! is_file( $path ) ) {
			wp_die( esc_html__( 'File unavailable.' ), '', array( 'response' => 404 ) );
		}
		$mime = (string) get_post_meta( $doc->ID, '_ff_mime', true );
		if ( ! in_array( $mime, self::ALLOWED, true ) ) {
			$mime = 'application/octet-stream';
		}
		$name = sanitize_file_name( $doc->post_title );

		nocache_headers();                                     // Never cache private files.
		header( 'Content-Type: ' . $mime );
		header( 'Content-Length: ' . filesize( $path ) );
		header( 'Content-Disposition: attachment; filename="' . $name . '"; filename*=UTF-8\'\'' . rawurlencode( $name ) );
		header( 'X-Content-Type-Options: nosniff' );
		header( "Content-Security-Policy: default-src 'none'; sandbox" );
		while ( ob_get_level() ) {
			ob_end_clean();
		}
		readfile( $path );
		exit;
	}
}
FF_Private_Docs::init();

Form and link markup

<?php if ( is_user_logged_in() ) : ?>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
	<input type="hidden" name="action" value="ff_upload">
	<?php wp_nonce_field( 'ff_upload', 'ff_nonce' ); ?>
	<label for="ff_file">Document (PDF, JPG or PNG, max 10 MB)</label>
	<input type="file" id="ff_file" name="ff_file" accept=".pdf,.jpg,.jpeg,.png" required>
	<button type="submit">Upload</button>
</form>
<?php endif; ?>

<?php
// Download link for document $id (nonce bound to the document ID):
$url = wp_nonce_url(
	add_query_arg( array( 'action' => 'ff_download', 'doc' => $id ), admin_url( 'admin-post.php' ) ),
	'ff_download_' . $id
);
echo '<a href="' . esc_url( $url ) . '">' . esc_html( get_the_title( $id ) ) . '</a>';
Design notes
  • The scanner hook returns null by default, so uploads are rejected until a scanner is wired in (fail closed). Hook ff_scan_upload to your host's or ClamAV's scanning API and return true only for a clean verdict. If you deliberately run without scanning for low-risk image-only uploads, make that an explicit, documented decision.
  • Grant ff_view_all_documents only to the roles that need it, using add_cap() on activation.
  • Error codes in the redirect are short identifiers mapped to friendly messages in the template. Never echo raw exception or path details to users.
  • Add a scheduled task to delete documents (file and post) past their retention period, and register exporter/eraser callbacks for privacy requests.
  • Never add a "temporary" bypass such as accepting any type for administrators, or disabling validation when a scan fails. Fix the cause using the troubleshooting database below.

PHP upload error codes

When an upload fails inside PHP, $_FILES['field']['error'] holds one of these values. Log it. It names the responsible layer precisely.

ValueConstantMeaningWhere to fix
0UPLOAD_ERR_OKSuccessNo error; any failure is later in the application
1UPLOAD_ERR_INI_SIZELarger than upload_max_filesizePHP configuration
2UPLOAD_ERR_FORM_SIZELarger than the form's MAX_FILE_SIZE hidden fieldForm markup (advisory only)
3UPLOAD_ERR_PARTIALOnly partially receivedNetwork, proxy timeouts, client aborted
4UPLOAD_ERR_NO_FILENo file sentForm field name, enctype="multipart/form-data" missing, JavaScript submission
6UPLOAD_ERR_NO_TMP_DIRTemporary folder missingServer: upload_tmp_dir / system temp directory
7UPLOAD_ERR_CANT_WRITEFailed to write to diskServer: disk full, quota, temp directory permissions
8UPLOAD_ERR_EXTENSIONA PHP extension stopped the uploadServer: security extensions; check PHP logs

Upload troubleshooting database

Each entry names the layer most likely responsible and how to confirm it. Work from the outside in: CDN/WAF → web server → PHP → WordPress → plugin. Never "fix" an upload problem by turning off validation, scanning or the WAF entirely. Find the specific limit or rule and adjust that one.

16 of 16 entries
HTTP 413 Content Too LargeCDN / web server
What you see
Upload fails immediately or at 100%; the browser or the media uploader reports "HTTP error" or "413"; the error page is styled by Nginx, Apache or the CDN, not WordPress.
Likely responsible layer
A request-body limit in front of PHP: the CDN plan limit, Nginx client_max_body_size, Apache LimitRequestBody, or ModSecurity SecRequestBodyLimit. PHP never sees the request.
How to investigate
Developer tools → Network: open the failing request and read the response Server header and body branding. Compare the file size with each layer's limit. Check whether the same upload works when bypassing the CDN (for example via a hosts-file entry to the origin, on staging).
Resolution
Raise the specific limit at the layer that responded, to a value that matches your application limit plus overhead. On managed hosting, ask the host. If the CDN plan limit is the cap, upload large files through a direct-to-storage flow instead.
Verification
Upload a file just below your application limit; confirm success and that oversized files now get your application's friendly error.
HTTP 403 Forbidden on uploadWAF / security
What you see
Upload request returns 403; sometimes only for certain files (PDFs with scripts, images with odd metadata) or certain users.
Likely responsible layer
A WAF (CDN, ModSecurity, host firewall) or a security plugin flagged the request body as malicious; or a server rule restricts async-upload.php or admin-ajax.php; or the nonce expired (WordPress returns 403 "The link you followed has expired").
How to investigate
Read the 403 response body: a CDN challenge page, ModSecurity message, security-plugin block page, or WordPress nonce message each look different. Check WAF event logs and the security plugin's log for the request time and rule ID. Retry after reloading the page to rule out an expired nonce.
Resolution
If a WAF false positive is confirmed, add a narrowly scoped exception (that rule ID, that path, authenticated users only), not a global disable. If the nonce expired, the page was cached or left open too long: exclude the page from caching.
Verification
The same file uploads successfully; WAF logs show no block; other WAF rules remain active.
HTTP 404 on upload or after uploadWeb server / WordPress
What you see
The upload request returns 404, or the file uploads but its URL returns 404.
Likely responsible layer
Upload endpoint blocked or rewritten (a "hide wp-admin" feature, a missing async-upload.php, a CDN rule); or for the file URL: wrong upload_path/upload_url_path options, a CDN rewrite pointing to the wrong host, an offload plugin moved the file, or Nginx rules deny/rewrite the path.
How to investigate
Note which request 404s. For file URLs, check that the file exists on disk at the expected path, compare the URL with Settings → Media and the home URL, and check CDN/offload plugin settings.
Resolution
Restore the endpoint access; correct the upload path settings (normally empty so WordPress uses wp-content/uploads); fix CDN or offload URL rewriting.
Verification
File URL returns 200 with the correct content type, directly and via the CDN.
HTTP 500 Internal Server Error during uploadPHP / server config
What you see
Generic 500 page or "HTTP error" in the media uploader; may only happen for large images.
Likely responsible layer
A PHP fatal error (often memory exhaustion while resizing images), a broken .htaccess in uploads (unsupported directive), or a crashed PHP worker.
How to investigate
Check the PHP error log and web server error log at the exact time. Enable WP_DEBUG_LOG temporarily (logging to a non-public path). Test with a small image: if small files work and large ones fail, suspect memory or image processing.
Resolution
Fix the fatal error at its source: raise WP_MAX_MEMORY_LIMIT within the server limit, reduce image dimensions, switch image editor (GD vs Imagick), or correct the .htaccess directive.
Verification
Large and small uploads succeed; error log clean.
PHP upload error codes (1–8)PHP
What you see
An error message containing a number, or a plugin log entry with an UPLOAD_ERR_* code.
Likely responsible layer
PHP's upload handling: size limits (1, 2), interrupted transfer (3), no file (4), temporary directory missing or unwritable (6, 7), or an extension blocking it (8).
How to investigate
Map the code using the table above in this chapter. For 6 and 7 check disk space (df -h), quotas and upload_tmp_dir in PHP info.
Resolution
Adjust the corresponding PHP setting or fix the server temp directory; codes 6, 7 and 8 normally need the host.
Verification
Upload succeeds and the application log records UPLOAD_ERR_OK.
"The uploaded file exceeds the upload_max_filesize directive in php.ini"PHP
What you see
Exact message in the media uploader; Media → Add New shows a "Maximum upload file size" lower than you need.
Likely responsible layer
PHP upload_max_filesize. WordPress displays the smaller of this and post_max_size.
How to investigate
Tools → Site Health → Info → Server shows the effective values. Check where they are set: the host panel's PHP settings, .user.ini, php.ini, or php_value in .htaccess (mod_php only).
Resolution
Raise upload_max_filesize (and post_max_size above it) using the method your host supports. Do not add php_value lines to .htaccess on PHP-FPM servers; they cause 500 errors.
Verification
Site Health shows the new value (it can take up to the user_ini.cache_ttl period, 5 minutes by default, for .user.ini changes to apply).
Maximum post size exceeded (form fields vanish, "link expired")PHP
What you see
After submitting a large upload, the page reloads with all fields empty, or WordPress says "The link you followed has expired"; no file error is shown.
Likely responsible layer
When the whole request exceeds post_max_size, PHP discards the entire body: $_POST and $_FILES are empty, so the nonce is missing too.
How to investigate
Compare the file size with post_max_size; look for "POST Content-Length of N bytes exceeds the limit" warnings in the PHP log.
Resolution
Raise post_max_size above upload_max_filesize with headroom; add client-side size checks for a friendlier message.
Verification
Large upload succeeds; the PHP log has no Content-Length warning.
Files upload but then disappearApplication / storage
What you see
Upload appears successful but the file is gone minutes or days later.
Likely responsible layer
A security scanner quarantined or deleted it; a form plugin deletes attachments after emailing them; a retention or clean-up job removed it; an offload plugin moved it to cloud storage and removed the local copy; a deployment or Git sync overwrote uploads; an ephemeral container filesystem was reset.
How to investigate
Check security plugin and host scanner quarantine logs; read the form plugin's file settings; review scheduled tasks (wp cron event list); check deploy scripts for rsync --delete on uploads; ask the host whether storage is persistent.
Resolution
Configure the responsible component: exclude legitimate files from overzealous rules, change form retention, exclude uploads from deployments, or use persistent or offloaded storage.
Verification
Uploaded files persist across a full scan and deploy cycle.
Files upload but do not appear in the Media LibraryWordPress / database
What you see
The file exists on disk (via SFTP) but there is no Media Library entry; or the library grid view is empty or spins forever.
Likely responsible layer
Files copied in by SFTP or a plugin without creating attachment posts; a database insert failed; the grid view's admin-ajax.php query is broken by a PHP error or plugin conflict; a filter restricts the library to the user's own uploads.
How to investigate
Switch to list view (upload.php?mode=list); check the browser console and the query-attachments AJAX response; check for PHP notices in the response; search the wp_posts table for the attachment.
Resolution
Import existing files properly (wp media import); fix the PHP error or plugin conflict breaking the AJAX response; review library-restriction plugins.
Verification
File appears in both grid and list views with thumbnails.
Permission denied / "Unable to create directory"Filesystem
What you see
"Unable to create directory wp-content/uploads/2026/12. Is its parent directory writable by the server?" or "The uploaded file could not be moved".
Likely responsible layer
The PHP user cannot write to uploads because of ownership or permissions after a migration or restore, a full disk or inode quota, or SELinux/AppArmor contexts on self-managed servers.
How to investigate
Check ownership and permissions (ls -la wp-content/), disk and inode usage (df -h, df -i), and the upload_path option (an absolute path from an old server is a common cause).
Resolution
Correct ownership to the PHP user (often via the host), set 755/644, free disk space, clear a stale upload_path. Never use 777.
Verification
A new year/month folder is created automatically on the next upload.
Image processing failure ("Post-processing of the image failed")PHP image library
What you see
WordPress uploads the original but warns that post-processing failed and suggests uploading a smaller image; thumbnails are missing.
Likely responsible layer
GD or Imagick ran out of memory or time while generating sub-sizes, Imagick resource limits were hit, or the image editor lacks support for the format (WebP/AVIF/HEIC).
How to investigate
Site Health → Info → Media Handling shows the active editor and supported formats; the PHP error log shows memory or time errors; try the same image resized smaller.
Resolution
Raise WP_MAX_MEMORY_LIMIT within server limits; reduce the number of registered image sizes; resize huge camera images before upload; ask the host to update or enable Imagick with the needed formats.
Verification
Thumbnails generate; wp media regenerate --only-missing completes for the affected attachment.
"Sorry, you are not allowed to upload this file type"WordPress
What you see
Exact message for SVG, JSON, CSV, font, ZIP or other files.
Likely responsible layer
The extension or detected MIME type is not in the allowed list, or the content check found the file's real type does not match its extension (for example a CSV detected as text/plain).
How to investigate
Confirm the extension is allowed (get_allowed_mime_types()), then check what finfo detects on a real sample.
Resolution
Add only the specific type needed via upload_mimes, mapped to the MIME type the server actually detects. For SVG use a sanitising plugin and restrict to trusted roles. Never define ALLOW_UNFILTERED_UPLOADS.
Verification
The specific type uploads; other unlisted types are still rejected.
Upload timeoutNetwork / PHP / proxy
What you see
Large uploads on slow connections fail after a fixed time (often 30, 60 or 100 seconds); 408, 504 or CDN timeout errors.
Likely responsible layer
max_input_time, max_execution_time, PHP-FPM request_terminate_timeout, Nginx client_body_timeout/fastcgi_read_timeout, Apache Timeout, or a CDN's origin timeout. Image processing after the transfer can also exceed the limit.
How to investigate
Time the failure and match it to the layer whose limit equals that duration; check whether it fails during transfer (progress bar) or after (processing).
Resolution
Raise the specific timeout moderately, or switch large-file flows to chunked or direct-to-storage uploads, which avoid long single requests.
Verification
A large test file uploads over a throttled connection (developer tools network throttling).
Storage quota exceededHosting
What you see
Uploads fail with write errors, backups fail, email to the hosting mailbox bounces; the host panel shows disk usage at 100%.
Likely responsible layer
Account disk or inode quota reached: often by backup archives stored on the server, cache folders, logs, or millions of image sub-sizes.
How to investigate
Find large directories (du -sh wp-content/* | sort -h), check inode usage, and look for backups, cache, debug.log and old staging copies.
Resolution
Move backups off-server, clear caches via their plugins, rotate logs, remove unused image sizes and regenerate, or increase the plan quota.
Verification
Free space and inodes return to a healthy margin; uploads succeed.
Memory exhaustion during uploadPHP
What you see
"Allowed memory size of N bytes exhausted" in logs; 500 errors on large images; works for small files.
Likely responsible layer
Decoding an image needs roughly width × height × 4 bytes or more per copy. A 6000 × 4000 photo needs about 96 MB per decoded copy, before any resizing work.
How to investigate
Read the exact limit in the error; compare with memory_limit and WP_MAX_MEMORY_LIMIT; check image dimensions.
Resolution
Raise the admin memory limit modestly within the host's cap; enforce maximum dimensions; resize before upload; prefer Imagick, which can be more memory-efficient for large images.
Verification
Uploads of maximum-allowed dimensions succeed; peak memory stays below the limit.
CDN / WAF rejects uploadsCDN / WAF
What you see
Upload blocked with a CDN-branded page, a challenge, or a 403/413/52x error; works when the CDN is bypassed.
Likely responsible layer
Body size limits, managed WAF rules matching content in the file, bot management challenging the uploader's AJAX request (which cannot solve challenges), or origin timeout limits.
How to investigate
Check CDN security event logs for the request (the ray or request ID shown on the error page helps); compare behaviour with the CDN bypassed on staging.
Resolution
Create a narrow exception: skip the specific managed rule for the upload endpoint for authenticated users; exclude upload endpoints from bot challenges; use direct-to-storage uploads for files above the CDN limit.
Verification
Uploads succeed through the CDN; security events show the exception applied only to the intended path.

Upload security checklist

  • Every upload path on the site is inventoried (Media Library, forms, profiles, plugins, REST/AJAX endpoints).
  • PHP cannot execute in wp-content/uploads/ (verified with a test file returning 403/404).
  • Extension allowlists are explicit and minimal; no SVG/HTML from untrusted users.
  • Server-side content detection (finfo / wp_check_filetype_and_ext) is applied to every custom upload handler.
  • Stored filenames are generated by the application, not taken from the client.
  • Application size limits are below PHP, web server and CDN limits.
  • Private documents are stored outside the web root or behind deny-all rules, and served only by an authenticated handler.
  • Download handlers check authentication, nonce, capability and ownership.
  • Anonymous upload forms have CAPTCHA or equivalent, rate limits and spam filtering.
  • Uploads with active content are malware-scanned; scan failures fail closed.
  • Directory listing is disabled for the uploads directory.
  • Retention periods are defined and enforced; uploads are covered by privacy export/erase processes.
  • ALLOW_UNFILTERED_UPLOADS is not defined and no role has unfiltered_upload.
  • Image libraries (GD/Imagick) and PHP are on currently patched versions.

Rather have someone else keep WordPress healthy?

Our managed hosting and care plans cover updates, backups, security monitoring and fixes like the ones in this handbook, so you can get on with running the business.

See Hosting & Care