命名约定上传的文件 [英] Naming convention uploaded files
问题描述
在我的网站上,我让用户上传文件。
如果文件有效并上传,它将被移动到一个文件夹(使用PHP)。 b
$ b
所有用户上传到同一个文件夹。
我想我需要重命名上传的文件。 b
是否有类似默认的命名约定让用户使用相同的文件名上传文件?
有没有标准的约定,但有几个最佳做法:
$ h
$ b
组织您的文件到(用户和/或日期)感知文件夹
类似于:
/ uploads / USER /或
/ uploads / [USER /] YEAR / [MONTH / [DAY / [HOUR / [MINUTE /]]]]
这会带来一些好处:
- 按用户和/或日期组织文件
- 使得难以达到文件的最大数量pe r目录
$ h
$ b(不)重命名/清理文件名
根据您的网站,用户群,您希望成为多么模糊,显然是您的架构,重命名与否是您必须作出的选择。您是否希望有一个名为
kate_at_the_beach.jpg
或1304357611.jpg
?这真的取决于你自己决定,但搜索引擎(明显地)像第一个更好。
你应该做的一件事是总是消毒并规范的文件名,个人,我只会允许以下字符:
0-9
,az
,AZ
,_
,-
,。
- 如果您选择这个卫生字母表。规范化基本上意味着只是将文件名转换为小写或大写(例如,如果您从区分大小写的文件系统切换到不区分大小写的文件系统(如Windows),则要避免丢失文件)。
以下是我在 phunction 中使用的示例代码(无耻的插件,我知道:P ):
$ filename ='/ etc / hosts / @ÁlixÃxel喜欢 - 啤酒?!。jpg';
$ filename = Slug($ filename,'_','。'); // etc_hosts_alix_axel_likes_beer.jpg
函数Slug($ string,$ slug =' - ',$ extra = null)
{
return strtolower(trim(preg_replace('〜[ preg_quote($ extra,'〜')。'] +〜i',$ slug,Unaccent($ string)),$ slug));
$ b $ ('');('');('');(UTF-8'),'&')!== false)
{
$ string = html_entity_decode(preg_replace('〜&([az] {1,2})急性| ig | ig | orn | ring | slash | tilde | uml);〜i','$ 1',$ string),ENT_QUOTES,'UTF-8');
}
return $ string;
b
$ h
$ b $ h处理重复的文件名h1>
如果目标文件
因此,在调用
之前move_uploaded_file()已经存在,它将被覆盖。 / code>你最好检查文件是否已经存在,如果是的话,你应该(如果你不想丢失旧文件)重新命名你的新文件,通常附加一个时间/随机/唯一标记 之前的文件扩展名,做这样的事情:
if(file_exists $ output。$ filename)=== true)
{
$ token ='_'。时间(); //见下面
$ filename = substr_replace($ filename,$ token,strrpos($ filename,'。',0);
}
move_uploaded_file($ _ FILES [$ input] ['tmp_name'],$ output。$ filename);
这会插入
$ token $ c $在文件扩展名之前,如上所述。至于
$ token
值的选择,您有几个选择:
- <
随机 > - 不是一个好主意,因为它不能保证唯一性,也不会处理重复的 - unique - 使用文件的散列内容 是我最喜欢的方式,因为它保证了 的唯一性并且节省了您的高清空间,因为您最多只能拥有2个相同的文件(一个带有原始文件名,另一个带有附加的散列),示例代码:
$ b(假的文本,以便下一行格式化为代码。)
$ token ='_ '。 md5_file($ _ FILES [$输入] [ tmp_name的值]);
希望有帮助! ;)
On my site I let users upload files.
If the file is valid and uploaded it is moved to a folder (using PHP).
All users upload to the same folder.
I think I need to rename the uploaded files.
Is there something like a default naming convention to let users upload files with the same filename?
解决方案There are no standard conventions, but there a couple of best-practices:
Organizing your files into (User and/or Date) Aware Folders
Something like:
/uploads/USER/ or /uploads/[USER/]YEAR/[MONTH/[DAY/[HOUR/[MINUTE/]]]]
This will have some benefits:
- organize files per user and/or date
- make it harder to reach the maximum number of files per directory
(Not) Renaming / Sanitizing Filenames
Renaming or not is a choice you will have to make, depending on your website, user base, how obscure you would like to be and, obviously your architecture. Would you prefer to have a file named
kate_at_the_beach.jpg
or1304357611.jpg
? This is really up to you to decide, but search engines (obviouslly) like the first one better.One thing you should do is always sanitize and normalize the filenames, personally I would only allow the following chars:
0-9
,a-z
,A-Z
,_
,-
,.
- if you choose this sanitation alphabet. normalization basically means just converting the filename to either lower or upper case (to avoid losing files if for instance you switch from a case sensitive file-system to a case insensitive one, like Windows).Here is some sample code I use in phunction (shameless plug, I know :P):
$filename = '/etc/hosts/@Álix Ãxel likes - beer?!.jpg'; $filename = Slug($filename, '_', '.'); // etc_hosts_alix_axel_likes_beer.jpg function Slug($string, $slug = '-', $extra = null) { return strtolower(trim(preg_replace('~[^0-9a-z' . preg_quote($extra, '~') . ']+~i', $slug, Unaccent($string)), $slug)); } function Unaccent($string) // normalizes (romanization) accented chars { if (strpos($string = htmlentities($string, ENT_QUOTES, 'UTF-8'), '&') !== false) { $string = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $string), ENT_QUOTES, 'UTF-8'); } return $string; }
Handling Duplicate Filenames
As the documentation entry on
move_uploaded_file()
states:If the destination file already exists, it will be overwritten.
So, before you call
move_uploaded_file()
you better check if the file already exists, if it does then you should (if you don't want to lose your older file) rename your new file, usually appending a time / random / unique token before the file extension, doing something like this:if (file_exists($output . $filename) === true) { $token = '_' . time(); // see below $filename = substr_replace($filename, $token, strrpos($filename, '.'), 0); } move_uploaded_file($_FILES[$input]['tmp_name'], $output . $filename);
This will have the effect of inserting the
$token
before the file extension, like I stated above. As for the choice of the$token
value you have several options:time()
- ensures uniqueness every second but sucks handling duplicate files- random - not a very good idea, since it doesn't ensure uniqueness and doesn't handle duplicates
- unique - using an hash of the file contents is my favorite approach, since it guarantees content uniqueness and saves you HD space since you'll only have at most 2 identical files (one with the original filename and another one with the hash appended), sample code:
(Dummy text so that the next line gets formatted as code.)
$token = '_' . md5_file($_FILES[$input]['tmp_name']);
Hope it helps! ;)
这篇关于命名约定上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!