string sanitizer for filename

后端 未结 17 1295
长情又很酷
长情又很酷 2020-11-27 13:23

I\'m looking for a php function that will sanitize a string and make it ready to use for a filename. Anyone know of a handy one?

( I could write one, but I\'m worri

相关标签:
17条回答
  • 2020-11-27 14:00

    / and .. in the user provided file name can be harmful. So you should get rid of these by something like:

    $fname = str_replace('..', '', $fname);
    $fname = str_replace('/',  '', $fname);
    
    0 讨论(0)
  • 2020-11-27 14:02

    The following expression creates a nice, clean, and usable string:

    /[^a-z0-9\._-]+/gi
    

    Turning today's financial: billing into today-s-financial-billing

    0 讨论(0)
  • 2020-11-27 14:03

    safe: replace every sequence of NOT "a-zA-Z0-9_-" to a dash; add an extension yourself.

    $name = preg_replace('/[^a-zA-Z0-9_-]+/', '-', strtolower($name)).'.'.$extension;
    
    0 讨论(0)
  • 2020-11-27 14:05

    Instead of worrying about overlooking characters - how about using a whitelist of characters you are happy to be used? For example, you could allow just good ol' a-z, 0-9, _, and a single instance of a period (.). That's obviously more limiting than most filesystems, but should keep you safe.

    0 讨论(0)
  • 2020-11-27 14:06

    $fname = str_replace('/','',$fname);

    Since users might use the slash to separate two words it would be better to replace with a dash instead of NULL

    0 讨论(0)
  • 2020-11-27 14:07

    Making a small adjustment to Sean Vieira's solution to allow for single dots, you could use:

    preg_replace("([^\w\s\d\.\-_~,;:\[\]\(\)]|[\.]{2,})", '', $file)
    
    0 讨论(0)
提交回复
热议问题