Skip to content

Kirby 4.4.1

$file

The $file object provides a set of methods that can be used when dealing with a single image or other media file, like getting the URL or resizing an image. It also handles file meta data.

You can extend this set of methods with custom file methods.

How to get a $file object

You can get a $file object to use with these methods by fetching it from the $site, a $page or a $user object.

Site file

<?php if ($file = $site->files()->first()): ?>
<img src="<?= $file->url() ?>" alt="">
<?php endif ?>

Page file

<?php if ($file = $page->files()->first()): ?>
<img src="<?= $file->url() ?>" alt="">
<?php endif ?>

User file

<?php if ($file = $user->files()->first()): ?>
<img src="<?= $file->url() ?>" alt="">
<?php endif ?>

Note how we use an if statement here to check if we have a file object before we call the url() method to prevent errors in case the page doesn't have any files. Never forget to do this in your own code.

Examples

Resizing a file

<?php if ($image = $page->image('myimage.jpg')): ?>
<img src="<?= $image->resize(300)->url() ?>" alt="">
<?php endif ?>