note 51825 added to features.file-upload
| From: | trog at swmud dot pl | Date: | Tue, 12 Apr 2005 11:07:07 +0000 |
| Subject: | note 51825 added to features.file-upload | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-87889@lists.php.net to get a copy of this message | ||
The best way of getting unique filenames, in order to
prevent accidental file overwriting during e.g. upload is
to use functions:
- uniqid
- time
- md5
It is not recommended to use just time() function.
The example code will explain.
The code:
<?php
for( $i = 0; $i < 10; $i++ )
echo 'Time: '.time().' ID: '.md5(uniqid(time())).".\n";
?>
Example output:
Time: 1113310579 ID: 79955ae9bc455a33aed92de6b83e1a4a.
Time: 1113310579 ID: 45de8a2173b53c33659cafa1d564f49a.
Time: 1113310579 ID: 9377a0e655efd206ca5583b6530706cd.
Time: 1113310579 ID: 06a86b2c9678adb7f222984019a14c10.
Time: 1113310579 ID: 25fe1664af35ebb3347f04cf703be968.
Time: 1113310579 ID: dca7397eb4d7d5c44e34b0a16a6fc89e.
Time: 1113310579 ID: fa01b6a2a83fbaefd89306d27835101f.
Time: 1113310579 ID: cf20ada42f2248c3c8b67f46b1d97401.
Time: 1113310579 ID: 9ab1a24c7f576fe0e6add43b848660ac.
Time: 1113310579 ID: c6aa6e9e314b4392c94432ece411824e.
The ids are unique and this is what we want.
Now just append or prepend this id to the original filename and we
have unique filename every time.
Example:
<?php
$unique_id = md5(uniqid(time()));
$filename = $unique_id.'_'.$filename;
?>
----
Manual Page -- http://www.php.net/manual/en/features.file-upload.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+51825
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51825&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51825&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51825&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51825&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51825&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+51825&report=yes
Search -- http://master.php.net/manage/user-notes.php