PHP: How to sanitize uploaded filenames?

后端 未结 6 1947
生来不讨喜
生来不讨喜 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:15

    To avoid filename collision just check whether given or generated filename doesn't already exists:

    do {
       // Generate filename, eg.:
       $filename = md5(uniqid()) . $fileExtension;
    } while (file_exists($filename));
    

    That gives you 100% sure that the filename is unique. Using md5 (or any other hash algorithm) ensures you that the filename is secure - and easy to handle.

提交回复
热议问题