Create a unique time-based file name for download without creating a race condition

I create a unique file name for uploaded files with the following code

$date = date( 'U' );
$user = $_SERVER[REMOTE_ADDR];
$filename = md5($date.$user);

The problem is that I want to use this file name again later in the script, but if the script takes a second to run, I am going to get a different file name the second time I try to use this variable.

For example, I use the upload / resize / save image script. The first script operation is to copy and save the modified image, in which I use the date function to assign a unique name. The script then processes the save and saves the entire load and gives it a name. At the end of the script ( $thumband $fullthese are the variables) I need to insert into the MySQL database the names of the files that I used when saving the downloads.

The problem is that sometimes large images require more than a second (or during the process, a second change), which leads to the fact that a different file name is placed in the database, and not that the file is actually saved.

Isn't it a good idea to use this naming method?

+5
6

AFAIK , file_exists() , , .

, . $_SESSION, cookie, GET .. pageloads.

,

+5

( AI). , , . MD5 , rand(), . rand(), , .

, , - PHP PHP. , "" . ( open dir dir ). is_uploaded_file() move_uploaded_file() : http://php.net/manual/en/features.file-upload.post-method.php 2 , .

, " ". - , , , . , , , , , . , - . .

+2

, php : uniqid. ( ?).

!

+2

$filename = md5(rand());

. , $filename , .

0

, - , . , ​​ uniqid(). , / / script "", .

To the problem itself. If I were you, I would just save the calculated file name for some variable using the variable from this point. A calculation already calculated is a waste of time. And when loading some really large images or several images at once, the script can take up to 20 seconds. You cannot depend on the fact that you will do whatever you want in one second.

0
source

All Articles