is there any built-in way to encode malicious file name characters when getting an asset URL through assetHandle.getUrl('transformationName')?

My system contains files with names such as /assets/images/foo/_transformationName/105 Flippy Dolphin 31 (F60).jpg and escaping the whole string escapes also slashes.

I can assemble a valid URL from asset.directory and asset.filename, but that cuts off access to image transformations.

I do realize I could create a twig extension or explode the string using regular expressions, do my thing and join it back, but I have a feeling this might use some approach more aimed at fixing the cause, not the consequence. The .getUrl() method might be able to return a web-safe value somehow maybe?


If you're worried about malicious characters in an uploaded file name, Craft already sanitizes them when uploading from the control panel.

Craft doesn't do this during Asset indexing because generally it's assumed that the files you're uploading are trusted files.

It sounds like that might not be true in your case, though. I can think of two options.

  1. Write a Craft plugin that loops through all files in your upload folders and calls the same AssetsHelper and IOHelper sanitizing methods that Craft does.

  2. Find some desktop application that does it before you upload the files. A quick Google search turned up this for OSX, and this for Windows.

  • It does not sanitize characters in a scenario where you upload thousands of files into the data directory and then hit the button for rebuilding asset indexes - which is my situation at the moment. The files are widely distributed across lots of subdirectories and it makes little sense to upload them manually.
    – Jan Klan
    Sep 23 '15 at 5:59
  • Updated my answer.
    – Brad Bell
    Sep 23 '15 at 20:04
  • I will write the plugin as a practice lesson and will publish it somehow somewhere when I am done with it. Thanks for the answer Brad.
    – Jan Klan
    Sep 24 '15 at 5:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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