x-yuri
x-yuri

Reputation: 18873

safe unique filename with no race condition

Is this a safe way to move uploaded file with respect to race conditions?

do { 
    $file = $path . "/" . uniqid() . '.' . $ext; 
    $fh = @fopen($file, 'x'); 
} while( ! $fh);
move_uploaded_file($src, $file);

UPD Besides learning other ways of solving the problem I would like to know if this code is subject to race conditions. AFAIU, fopen with 'x' mode and move_uploaded_file are atomic, so no collision could be possible.

On top of that and with regards to "uniqid will suffice", several people in comments to tempnam stated necessity of using fopen with 'x' mode to avoid race conditions. Do they overly paranoid? I think, having safer solution is better, if it doesn't make code significantly complex.

Upvotes: 1

Views: 736

Answers (1)

arkascha
arkascha

Reputation: 42925

PHP's tempnam function guarantees the uniqueness. Or you can use a filename that is based on a microtimestamp (which won't work under MS-Windows...).

Upvotes: 1

Related Questions