wp_filesize()WP 6.0.0

Wrapper for PHP filesize with filters and casting the result as an integer.

The wp_filesize function is useful when storing attachments on third-party storage (Amazon's S3, Google Cloud storage, or a network share such as NFS). This means that the value can be filtered, preventing the possibility of slow access to the external server.

1 time — 0.0000501 sec (very fast) | 50000 times — 0.23 sec (very fast) | PHP 7.4.25, WP 6.0
Hooks from the function

Return

Int. The size of the file in bytes, or 0 in the event of an error.

Usage

wp_filesize( $path );
$path(string) (required)
Path to the file.

Examples

0

#1 Get the file size through the WP function

Example when a file exists:

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

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

When the file does not exist:

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

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

Changelog

Since 6.0.0 Introduced.

wp_filesize() code WP 6.4.3

function wp_filesize( $path ) {
	/**
	 * Filters the result of wp_filesize before the PHP function is run.
	 *
	 * @since 6.0.0
	 *
	 * @param null|int $size The unfiltered value. Returning an int from the callback bypasses the filesize call.
	 * @param string   $path Path to the file.
	 */
	$size = apply_filters( 'pre_wp_filesize', null, $path );

	if ( is_int( $size ) ) {
		return $size;
	}

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

	/**
	 * Filters the size of the file.
	 *
	 * @since 6.0.0
	 *
	 * @param int    $size The result of PHP filesize on the file.
	 * @param string $path Path to the file.
	 */
	return (int) apply_filters( 'wp_filesize', $size, $path );
}