Using WordPress ‘check_upload_size()’ PHP function

The check_upload_size() WordPress PHP function checks if an uploaded file exceeds the allowed space quota.

Usage

Let’s say we have a file we want to upload named ‘my_file’. Here’s how we could use the function:

$file = $_FILES['my_file'];
$result = check_upload_size($file);

if (!$result) {
    echo "File size exceeds the maximum allowed quota";
} else {
    echo "File size is within the allowed quota";
}

Parameters

  • $file (array) – This is a required parameter. It represents an element from the $_FILES array for the file we are checking.

More information

See WordPress Developer Resources: check_upload_size()

This function was introduced in WordPress 3.0. It is not deprecated and is still actively used. The source code for this function can be found in the file wp-admin/includes/ms.php. Related functions include wp_handle_upload and wp_check_filetype_and_ext.

Examples

Basic Usage

// Get the file
$file = $_FILES['user_file'];

// Check the size
$is_within_quota = check_upload_size($file);

// Output the result
echo $is_within_quota ? 'Within quota' : 'Exceeds quota';

This example checks if ‘user_file’ is within the quota, and then outputs the result.

Checking Multiple Files

// Get multiple files
$files = $_FILES['user_files'];

foreach ($files as $file) {
    // Check the size of each file
    $is_within_quota = check_upload_size($file);

    // Output the result
    echo $is_within_quota ? 'Within quota' : 'Exceeds quota';
}

In this example, we’re checking multiple files (in ‘user_files’) for whether they’re within the quota.

Uploading File Only If It’s Within Quota

// Get the file
$file = $_FILES['user_file'];

// Check the size
$is_within_quota = check_upload_size($file);

if ($is_within_quota) {
    move_uploaded_file($file['tmp_name'], "/uploads/" . $file['name']);
} else {
    echo 'File exceeds quota';
}

This code checks if ‘user_file’ is within the quota. If it is, it moves the uploaded file to the ‘uploads’ directory. Otherwise, it outputs an error message.

Checking File Size Before Inserting Into Media Library

// Get the file
$file = $_FILES['user_file'];

// Check the size
$is_within_quota = check_upload_size($file);

if ($is_within_quota) {
    // Insert file into media library
    media_handle_upload($file);
} else {
    echo 'File exceeds quota';
}

This example checks if ‘user_file’ is within the quota. If it is, it inserts the file into the media library. If it’s not, it outputs an error message.

Verifying File Size Before Updating User Avatar

// Get the file
$file = $_FILES['user_avatar'];

// Check the size
$is_within_quota = check_upload_size($file);

if ($is_within_quota) {
    // Update the user avatar
    update_user_meta(get_current_user_id(), 'user_avatar', $file);
} else {
    echo 'Avatar file exceeds quota';
}

In this example, the ‘user_avatar’ file is checked for size. If it’s within the quota, the user avatar is updated.