php - 清理字符串以使其 URL 和文件名安全?

标签 php url filenames sanitization

我正在尝试提出一个函数,该函数可以很好地清理某些字符串,以便它们可以安全地在 URL 中使用(如 post slug)并且也可以安全地用作文件名。例如,当有人上传文件时,我想确保从名称中删除所有危险字符。

到目前为止,我已经提出了以下功能,希望可以解决这个问题并允许外国的 UTF-8 数据。

/**
 * Convert a string to the file/URL safe "slug" form
 *
 * @param string $string the string to clean
 * @param bool $is_filename TRUE will allow additional filename characters
 * @return string
 */
function sanitize($string = '', $is_filename = FALSE)
{
 // Replace all weird characters with dashes
 $string = preg_replace('/[^\w\-'. ($is_filename ? '~_\.' : ''). ']+/u', '-', $string);

 // Only allow one dash separator at a time (and make string lowercase)
 return mb_strtolower(preg_replace('/--+/u', '-', $string), 'UTF-8');
}

是否有人有任何棘手的示例数据可供我对照 - 或者知道保护我们的应用免受不良名称影响的更好方法?

$is-filename 允许一些额外的字符,例如临时 vim 文件

更新:删除了星号,因为我想不出一个有效的用途

最佳答案

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

关于php - 清理字符串以使其 URL 和文件名安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2668854/

相关文章:

javascript - 如果 URL 以/斜杠结尾,则获取 window.location.href 返回页面名称和扩展名

security - 从 URL 地址中删除/隐藏端口号

c# - 从 C# 中的 URI 字符串获取文件名

Git复制文件保存历史

php - 即时 SSL 检测

PHP 将变量移动到另一个文档

php - 如果对象在同一类中实例化,则可以公开调用私有(private)函数

javascript - 如何在javascript中调用url?

php - 当指定 SELECT FROM row 时 MySQL 返回数组

django - 使用 FileField 在 Django 中保存原始文件名