2014-07-20 66 views
2

我有一个随机字符串,散列(MD5/SHA1),uniqid()或时间戳或更换等文件名.....如何上传前用PHP来获得安全的文件名

示例使用uniqid():

9d24707b98e4ddfae9e321ef4f502241.jpg 

例WordPress的sanitiza文件名功能:

function sanitize_file_name($filename) { 
      $filename_raw = $filename; 
      $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0)); 
      /** 
      * Filter the list of characters to remove from a filename. 
      * 
      * @since 2.8.0 
      * 
      * @param array $special_chars Characters to remove. 
      * @param string $filename_raw Filename as it was passed into sanitize_file_name(). 
      */ 
      $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw); 
      $filename = preg_replace("#\x{00a0}#siu", ' ', $filename); 
      $filename = str_replace($special_chars, '', $filename); 
      $filename = preg_replace('/[\s-]+/', '-', $filename); 
      $filename = trim($filename, '.-_'); 

      // Split the filename into a base and extension[s] 
      $parts = explode('.', $filename); 

     // Return if only one extension 
      if (count($parts) <= 2) { 
        /** 
        * Filter a sanitized filename string. 
        * 
       * @since 2.8.0 
        * 
        * @param string $filename  Sanitized filename. 
       * @param string $filename_raw The filename prior to sanitization. 
        */ 
        return apply_filters('sanitize_file_name', $filename, $filename_raw); 
      } 

      // Process multiple extensions 
      $filename = array_shift($parts); 
      $extension = array_pop($parts); 
      $mimes = get_allowed_mime_types(); 

      /* 
      * Loop over any intermediate extensions. Postfix them with a trailing underscore 
      * if they are a 2 - 5 character long alpha string not in the extension whitelist. 
      */ 
      foreach ((array) $parts as $part) { 
        $filename .= '.' . $part; 

        if (preg_match("/^[a-zA-Z]{2,5}\d?$/", $part)) { 
          $allowed = false; 
          foreach ($mimes as $ext_preg => $mime_match) { 
            $ext_preg = '!^(' . $ext_preg . ')$!i'; 
            if (preg_match($ext_preg, $part)) { 
              $allowed = true; 
              break; 
            } 
          } 
          if (!$allowed) 
            $filename .= '_'; 
        } 
      } 
      $filename .= '.' . $extension; 
      /** This filter is documented in wp-includes/formatting.php */ 
      return apply_filters('sanitize_file_name', $filename, $filename_raw); 
    } 

我的方法是安全/安全的方式还是我需要清理的文件名与任何类/函数或两者路 组合?

回答

0

要做的最好的事情是有一个磁盘上的文件名不是由用户根据任何可预测的数据。您可以简单地使用资产的ID号作为其数据库中的元数据。没有文件扩展名。不要将它放在Web服务器的文档根目录下。

+0

你说得对。你能告诉我更多细节吗?或任何示例/文档? –

+0

@ user3142680没有什么可以真正添加的......在你的数据库中,你将存储一个带有原始文件信息的记录,比如原来的名字(尽管这些日子不是很有用),内容类型(例如“text/plain”),也许是一个校验和,以及其他你需要的东西(比如拥有它的用户的ID)。这个记录会有一个ID,比如'23'或其他东西,你可以在磁盘上命名你的文件。 '/选择/你的应用程序/资产/ 23'。而已。没有文件扩展名。由于数据库的原子性质,您保证具有唯一的ID,并且可以将其用作文件名。 – Brad