File()->uri() produces an error

When I’m working on localhost, the path I get is always "Users/[user]/Sites/...../image.jpg", which in turn outputs
<img src="Users/[user]/Sites/...../image.jpg"> and that can’t be shown.

On the server I get

<img src="server.name.tld/var/usr/.../web">, so I get the siteurl+absolutePath, which also isn’t pointing to the image. What would be nice is "content/stuff/substuff/image.jpg" or something like that. But I can’t, for the love of god, find out, why it isn’t returning it like this.

Now I realize… maybe that would have been the better question… why is findBy() outputting the absolute path instead of the relative path from the url…

I have tried that locally and couldn’t reproduce it. I always get a File object. Which Kirby version do you use?

I’m using Kirby 2.3.1

I tried debugging this step by step but if I var_dump the $entry variable, I get a blank page and PHP throws a tantrum about insufficient memory…

So, without using var_dump, I tried figuring out the file type with gettype:

$entry ---- object
$entry->files() ------ object
$entry->files()->findBy(‘name’, ‘titleimg’) ------ object
$entry->files()->findBy(‘name’, ‘titleimg’)->url() ------ Fatal error: Call to a member function url() on a non-object in

I don’t get it ._.

Edit: Maybe it’s a server configuration issue?

And what does the following return?

var_dump(get_class($entry->files()->findBy('name', 'titleimg')));

This shouldn’t be a server configuration issue, but maybe some plugin is interfering with Kirby?

Either string(4) “File” or string(3) “Tpl”

I guess I get “File” only on those subpages, where there’s actually an image.

As for Plugins: I don’t have any installed…

Well, that’s interesting. Tpl is Kirby’s internal class to read snippets and that has absolutely nothing to do with file handling. So I’m very surprised that you get this result.

Can you reproduce this issue in a fresh installation of the starterkit?

I can in fact reproduce this in a starterkit. If the image does not exist, the above code returns ‘Tpl’, otherwise ‘File’.

Nevertheless, the following code should produce the right result:

<?php if($image = $entry->files()->findBy('name', 'titleimg')) {
    echo $image->uri();
}
?>
1 Like

I can now reproduce this. I didn’t test with files that don’t exist.

There’s a pretty simple explanation why get_type() returns Tpl for files that don’t exist: In that case, the returned file is null, and get_class(null) returns the current class. When you put that line inside a template or snippet, that is of course Tpl.

This means that this is a not a bug in Kirby (Kirby does not actually return a Tpl instance, just null, which is not an object). The fix proposed by @texnixe in the post above is the correct solution.