wp_filesize()WP 6.0.0

Получает размер указанного файла.

Обертка для PHP filesize() с фильтрами и преобразованием результата в целое число.

Функция wp_filesize полезна при хранении attachments на стороннем хранилище (Amazon’s S3, Google cloud storage или в общем сетевом ресурсе, таком как NFS). Это означает, что значение может быть отфильтровано, что предотвращает возможность медленного обращения к внешнему серверу.

1 раз — 0.0000501 сек (очень быстро) | 50000 раз — 0.23 сек (очень быстро) | PHP 7.4.25, WP 6.0
Хуки из функции

Возвращает

int. Размер файла в байтах, или 0 в случае ошибки.

Использование

wp_filesize( $path ): int;
$path(строка) (обязательный)
Путь к файлу, размер которого нужно получить.

Примеры

#1 Получим размер файла через функцию ВП

Пример когда файл существует:

$path = '/path/to/file.png';
$size = wp_filesize( $path );

var_dump( $size ); // int(60235)

Когда файл не существует:

$path = '/path/to/nonexistent-file.png';
$size = wp_filesize( $path );

var_dump( $size ); // int(0)

Список изменений

С версии 6.0.0 Введена.
С версии 7.1.0 The return value is now ensured to always be greater than or equal to zero.

Код wp_filesize() WP 7.1

function wp_filesize( $path ): int {
	/**
	 * Filters the result of wp_filesize() before the file_exists() PHP function is run.
	 *
	 * @since 6.0.0
	 * @since 7.1.0 Negative values are now ignored, being treated the same as null. Numeric values are cast to integers.
	 *
	 * @param null|int $size The unfiltered value. Returning a non-negative number from the callback bypasses the filesize call.
	 * @param string   $path Path to the file.
	 */
	$size = apply_filters( 'pre_wp_filesize', null, $path );
	if ( is_numeric( $size ) ) {
		$size = (int) $size;
	}
	if ( is_int( $size ) && $size >= 0 ) {
		return $size;
	}

	$size = file_exists( $path ) ? (int) filesize( $path ) : 0;

	/**
	 * Filters the size of the file.
	 *
	 * @since 6.0.0
	 * @since 7.1.0 The return value is now always zero or greater. Numeric values are cast to integers.
	 *
	 * @param int    $size The result of PHP filesize on the file.
	 * @param string $path Path to the file.
	 */
	$size = apply_filters( 'wp_filesize', $size, $path );
	if ( is_numeric( $size ) ) {
		$size = (int) $size;
	} else {
		$size = 0;
	}
	return max( 0, $size );
}
4 комментария