It seems that some of our users are uploading filenames with foreign characters...

uploaded files

Is there any way to prevent this?

I'd like to keep the filenames to all English letters (plus numbers, dash & underscore).

(If relevant, this is for Craft 2.)

  • I'm not sure how you'd intelligently map non-roman characters to roman characters. Is there a reason you need to exclude foreign characters? Mar 21 '18 at 18:36
  • Long story... these images get pushed out in a weekly email. Then that email gets forwarded via a GroupMail process (which I am not familiar with). The foreign characters seem to be breaking GroupMail.
    – Lindsey D
    Mar 21 '18 at 18:44
  • Honestly, even just stripping them out would work. The actual filenames are unimportant, so even replacing each one with a timestamp might be sufficient.
    – Lindsey D
    Mar 21 '18 at 18:44

Cant you just use preg_replace("/[^A-Za-z0-9 ]/", '', $stuff) for this? Seems that will strip away anything that isnt a number or a letter from the english alphabet?

EDIT --------- Challenge accepted ;)

public function modifyAssetFilename($filename){
    return preg_replace("/[^A-Za-z0-9-]/", '', $filename);

Something according to the above strips out all unwanted characters using the hook if you place it in a plugins main class file. The above preg_replace should also keep dashes e.t.c.

Another way you might be able to approach the sanitation of filenames is listening to the onBeforeSaveAsset method and then using craft()->assets->renameFile() once you have sanitized it. Not sure which one is better. Both should work.

  • Based on my own research, looks like you're halfway there. If your answer mentioned how to use this in the context of the modifyAssetFilename hook, I would mark it as correct.
    – Lindsey D
    Mar 21 '18 at 19:41
  • Excellent, thank you! I also appreciate the alternative option.
    – Lindsey D
    Mar 21 '18 at 20:06

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.