如何知道文件名在当前平台上是否有效?

时间:2013-07-13 11:11:56

标签: php filesystems

所有平台(可能还有文件系统)对于允许哪些字符作为文件或目录名称有不同的规则。此外,某些系统具有文件名黑名单:例如,在Windows上,com1是无效的文件名。

有没有办法以编程方式了解在PHP中计算有效文件名的规则?

作为替代方案,除了[0-9a-zA-Z]之外,是否有可信任的安全字符列表保证在任何系统上有效?

请注意,基于的解决方案尝试保存,如果失败,则文件名无效对我的用例是不可接受的。

1 个答案:

答案 0 :(得分:2)

已经回答得很好,Sanitizing strings to make them URL and filename safe?

  

我在Chyrp代码中找到了这个更大的功能:

/**
 * Function: sanitize
 * Returns a sanitized string, typically for URLs.
 *
 * Parameters:
 *     $string - The string to sanitize.
 *     $force_lowercase - Force the string to lowercase?
 *     $anal - If set to *true*, will remove all non-alphanumeric characters.
 */
function sanitize($string, $force_lowercase = true, $anal = false) {
    $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
                   "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
                   "—", "–", ",", "<", ".", ">", "/", "?");
    $clean = trim(str_replace($strip, "", strip_tags($string)));
    $clean = preg_replace('/\s+/', "-", $clean);
    $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
    return ($force_lowercase) ?
        (function_exists('mb_strtolower')) ?
            mb_strtolower($clean, 'UTF-8') :
            strtolower($clean) :
        $clean;
}
     

wordpress代码

中的这个
/**
 * Sanitizes a filename replacing whitespace with dashes
 *
 * Removes special characters that are illegal in filenames on certain
 * operating systems and special characters requiring special escaping
 * to manipulate at the command line. Replaces spaces and consecutive
 * dashes with a single dash. Trim period, dash and underscore from beginning
 * and end of filename.
 *
 * @since 2.1.0
 *
 * @param string $filename The filename to be sanitized
 * @return string The sanitized filename
 */
function sanitize_file_name( $filename ) {
  $filename_raw = $filename;
  $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`",
  "!", "{", "}");
  $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
  $filename = str_replace($special_chars, '', $filename);
  $filename = preg_replace('/[\s-]+/', '-', $filename);
  $filename = trim($filename, '.-_');
  return apply_filters('sanitize_file_name', $filename, $filename_raw);
}
     

2012年9月更新

     

Alix Axel已经完成了   在这方面做了一些不可思议的工作。他的功能框架包括   几个伟大的文本过滤器和转换。