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


How to know if a file name is valid on the current platform?

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

有没有一种方法可以通过编程方式了解PHP中计算有效文件名的规则

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

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

已经回答得很好了,对字符串进行消毒以确保它们的URL和文件名安全吗?

我在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做到了这方面的一些令人难以置信的工作。他的功能框架包括几个很棒的文本过滤器和转换。

  • 不合格
  • Slug
  • 过滤器