Same name and namespace in other branches
  1. 6.x includes/file.inc \file_validate_size()
  2. 7.x includes/file.inc \file_validate_size()
  3. 8.9.x core/modules/file/file.module \file_validate_size()
  4. 9 core/modules/file/file.module \file_validate_size()

Checks that the file's size is below certain limits.

Parameters

\Drupal\file\FileInterface $file: A file entity.

int $file_limit: (optional) The maximum file size in bytes. Zero (the default) indicates that no limit should be enforced.

int $user_limit: (optional) The maximum number of bytes the user is allowed. Zero (the default) indicates that no limit should be enforced.

Return value

array An empty array if the file size is below limits or an array containing an error message if it's not.

Deprecated

in drupal:10.2.0 and is removed from drupal:11.0.0. Use the 'file.validator' service instead.

See also

https://www.drupal.org/node/3363700

hook_file_validate()

1 call to file_validate_size()
LegacyValidatorTest::testFileValidateSize in core/modules/file/tests/src/Kernel/LegacyValidatorTest.php
Tests file_validate_size().
2 string references to 'file_validate_size'
LegacyFileThemeTest::testTemplatePreprocessFileUploadHelp in core/modules/file/tests/src/Kernel/LegacyFileThemeTest.php
@covers ::template_preprocess_file_upload_help
template_preprocess_file_upload_help in core/modules/file/file.module
Prepares variables for file upload help text templates.

File

core/modules/file/file.module, line 192
Defines a "managed_file" Form API field and a "file" field for Field module.

Code

function file_validate_size(FileInterface $file, $file_limit = 0, $user_limit = 0) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'file.validator\' service instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
  $user = \Drupal::currentUser();
  $errors = [];
  if ($file_limit && $file
    ->getSize() > $file_limit) {
    $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', [
      '%filesize' => ByteSizeMarkup::create($file
        ->getSize()),
      '%maxsize' => ByteSizeMarkup::create($file_limit),
    ]);
  }

  // Save a query by only calling spaceUsed() when a limit is provided.
  if ($user_limit && \Drupal::entityTypeManager()
    ->getStorage('file')
    ->spaceUsed($user
    ->id()) + $file
    ->getSize() > $user_limit) {
    $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', [
      '%filesize' => ByteSizeMarkup::create($file
        ->getSize()),
      '%quota' => ByteSizeMarkup::create($user_limit),
    ]);
  }
  return $errors;
}