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);
}
我的方法是安全/安全的方式還是我需要清理的文件名與任何類/函數或兩者路 組合?
你說得對。你能告訴我更多細節嗎?或任何示例/文檔? –
@ user3142680沒有什麼可以真正添加的......在你的數據庫中,你將存儲一個帶有原始文件信息的記錄,比如原來的名字(儘管這些日子不是很有用),內容類型(例如「text/plain」),也許是一個校驗和,以及其他你需要的東西(比如擁有它的用戶的ID)。這個記錄會有一個ID,比如'23'或其他東西,你可以在磁盤上命名你的文件。 '/選擇/你的應用程序/資產/ 23'。而已。沒有文件擴展名。由於數據庫的原子性質,您保證具有唯一的ID,並且可以將其用作文件名。 – Brad