By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,716 Members | 1,447 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,716 IT Pros & Developers. It's quick & easy.

problem with file_exists caching even when clearstatcache() is called

P: n/a
Hi guys,

I've created this little function to check whether a user has uploaded a
file with the same name as an existing file, and if so rename it to
file-1.jpg, file-2.jpg etc.

clearstatcache();
if(file_exists("$BasePath/$FileName.jpg")){
$extra=1;
while(file_exists("$BasePath/$FileName-$extra.jpg")){
$extra++;
}
$FileName="$FileName-$extra";
}

However if files are deleted outside PHP file_exists still returns true so
it keeps adding higher numbers to the files.
Is there any way I can get round this? The strange thing is if I call
file_exists() on a folder it works fine.

--
Regards,
Andrew Crowe
Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Sorry forgot to mention I'm using PHP5 RC2 on Windows 2000 / IIS (isapi)

--
Regards,
Andrew Crowe
Jul 17 '05 #2

P: n/a
"Andrew Crowe" <an************@yahoo.co.uk> wrote in message
news:40**********************@news.easynet.co.uk.. .
Hi guys,

I've created this little function to check whether a user has uploaded a
file with the same name as an existing file, and if so rename it to
file-1.jpg, file-2.jpg etc.

clearstatcache();
if(file_exists("$BasePath/$FileName.jpg")){
$extra=1;
while(file_exists("$BasePath/$FileName-$extra.jpg")){
$extra++;
}
$FileName="$FileName-$extra";
}

However if files are deleted outside PHP file_exists still returns true so
it keeps adding higher numbers to the files.
Is there any way I can get round this? The strange thing is if I call
file_exists() on a folder it works fine.

--
Regards,
Andrew Crowe


There's a race condition in your code. Between the time when file_exists()
was called and the subsequent move_uploaded_file() a file with that name
could conceivably have been created. A better approach is to keep calling
move_uploaded_file() until it works:

$extra = 1;
while(!@move_upload_file($tmpname, $filename)) {
$filename = "$BasePath/$FileName-$extra.jpg";
$extra++;
}

This bypasses the caching issue as well.
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.