Skip to content

Core\IO\Metadata::size

$metadata->size(): uint

Returns the size of a file in bytes.

$info->size() works on the Core\IO\Metadata value that Core\IO::metadata returns. It returns a uint: the number of bytes the file had when metadata was called. An empty file has a size of 0.

The size counts bytes, not characters. A character such as ü uses 2 bytes, so a text of 6 characters can be 8 bytes long.

The value does not change when the file changes later. To get the new size, call metadata again. The size of a folder is a number the operating system chooses, and it means different things on different systems.

Return value

Returns uint. The byte count as a uint. For a directory, the number depends on the platform and has no portable meaning.

Examples

Count the bytes of a file

<?nvs
// Shows how to read the size of a file in bytes.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'greeting.txt');
Core\IO::write($path, "Grüße\n");
var $info = Core\IO::metadata($path);
// `size` counts bytes, not characters. "ü" and "ß" use 2 bytes each.
// This prints "6 characters" and "8 bytes".
echo Core\Str::length("Grüße\n"), ' characters', "\n";
echo $info->size(), ' bytes', "\n";
Output
6 characters
8 bytes

An empty file

<?nvs
// Shows how to check if a file is empty before the program reads it.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'queue.txt');
Core\IO::write($path, '');
// An empty file has a size of 0. This prints "nothing to do".
if (Core\IO::metadata($path)->size() == 0) {
echo 'nothing to do', "\n";
} else {
echo Core\IO::read($path);
}
// After a write, the size is not 0, so this prints "send the report".
Core\IO::write($path, "send the report\n");
if (Core\IO::metadata($path)->size() == 0) {
echo 'nothing to do', "\n";
} else {
echo Core\IO::read($path);
}
Output
nothing to do
send the report

Refuse an upload that is too large

<?nvs
// Shows how a program accepts an uploaded file only when it is not larger than a limit.
string $dir = Core\Path::join(Core\IO::createTemporaryDirectory(), 'incoming');
Core\IO::makeDirectory($dir);
Core\IO::write(Core\Path::join($dir, 'avatar.png'), Core\Str::repeat('x', 800));
Core\IO::write(Core\Path::join($dir, 'holiday.jpg'), Core\Str::repeat('x', 2048));
// The limit is 1024 bytes. A larger file is rejected and deleted.
// This prints "avatar.png: accepted, 800 bytes" and "holiday.jpg: rejected, 2048 bytes".
uint $limit = 1024;
foreach (Core\Arr::sort(Core\IO::list($dir)) as string $name) {
string $path = Core\Path::join($dir, $name);
uint $size = Core\IO::metadata($path)->size();
if ($size > $limit) {
Core\IO::remove($path);
echo $name, ': rejected, ', $size, ' bytes', "\n";
} else {
echo $name, ': accepted, ', $size, ' bytes', "\n";
}
}
Output
avatar.png: accepted, 800 bytes
holiday.jpg: rejected, 2048 bytes