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
- Logged-in user submits the form to
admin-post.php (no nopriv hook, so anonymous requests never reach the handler).
- 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.
- File moved to private storage under a random name; ownership and metadata recorded on a private custom post type.
- Downloads go through a handler that checks login → nonce bound to the document → existence → ownership or staff capability, then streams with safe headers.
- 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.