5

I am generating dynamic images to a directory in craft/storage. I need to be able to use these generated images on the front-end inside templates. Is there a helper method for this, or some way to use these images in my templates?

1 Answer 1

4

Craft 2:

Since craft/storage/ is not publicly accessible, your only real option here is to serve them through Craft as Resource Requests. (This is the vehicle through which Craft serves up all of the CP’s front end resources, which live in craft/app/resources/.)

The actual resource URLs will depend on the site’s resourceTrigger config setting, so to generate the URLs you should use URLHelper::getResourceUrl():

$url = UrlHelper::getResourceUrl('myplugin/some/path.jpg');

Your templates can call the corresponding resourceUrl() function as well:

{{ resourceUrl('myplugin/some/path') }}

Then you will need to add a getResourcePath hook method to your primary plugin class, which would detect incoming resource requests and resolve them to the actual server path in craft/storage/.

public function getResourcePath($path)
{
    // Does this path start with "myplugin/"?
    if (strncmp($path, 'myplugin/', 9) == 0)
    {
        // Return the path to the file in craft/storage/
        return craft()->path->getStoragePath().'myplugin/'.substr($path, 9);
    }
}

It’s worth mentioning that you’re always going to get worse performance out of serving files through PHP than you would if they were located somewhere that’s publicly accessible. So you might just want to have the user create a new folder somewhere under their web root, and have them specify the path/URL to that folder, just like local asset sources.

Craft 3+:

In Craft 3+, your plugin can define an asset bundle whose sourcePath points to the source folder in storage/.

4
  • Is there a way to find the 'public' folder? I can't find anything in PathService or constants. Commented Nov 11, 2016 at 22:44
  • @ElliotLewis Sorry just saw your comment. Can you please post that as a new question? Commented Feb 27, 2017 at 19:12
  • any updates for newer versions of craft?
    – tenshi
    Commented Aug 21, 2023 at 7:56
  • @tenshi Just added a note for Craft 3+. Commented Aug 24, 2023 at 15:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.