PHP: How to sanitize uploaded filenames?

后端 未结 6 1950
生来不讨喜
生来不讨喜 2021-01-02 11:32

I have a PHP application.

I allow users to upload files to my web application.

Question: What\'s the best way for me to sanitize the file n

6条回答
  •  佛祖请我去吃肉
    2021-01-02 12:07

    I would just run a simple regex that replaces any non alphanumeric characters with an underscore (or just remove these character altogether). Make sure you preserve the extension of course.

    If you want to go a bit further, you could use magic mime extension to ensure the file is the same format that the extension says it is.

    EDIT: To avoid filename collisions in a directory, you could append a md5 of users IP + current time to the filename.

提交回复
热议问题