Jump to content

PHP and file_exists paranoia


Lanselot

Recommended Posts

I have a code that's supposed to work in the following way:

 

Generate a random number, check if a file exists with that number as filename. If it exists, then sum one to the number until a filename with that number doesn't exist.

 

$new_name = rand(0,99999);
$ext = substr($origen,-4,4); //Retrieves file extension
while (file_exists($base.'images/'.$new_name.$ext)) {
  $new_name++;
}

 

Plain simple... well, the problem is that every some thousands, I get duplicated filenames, which shouldn't be possible.

Am I missing any scenario?

 

Thank you in advance.

Link to comment
https://forums.phpfreaks.com/topic/69516-php-and-file_exists-paranoia/
Share on other sites

Well, the above code is in a function, and right before it's called the following is executed:

 

$rscimage = getimagesize($base.'images/'.$file);
     if ($rscimage[2] > 2) { //Delete if not GIF,JPG
        unlink($base.'images/'.$file);
     }
$result = rand_rename($file,$rscimage); //That's the function above

 

Also in the original code(not simplified for posting), there's an escaped variable among the filename, maybe it has something to do?. Scopes are ok too.

You will always get duplicate randoms, no matter how high your source variation is, especially over enough random generations.

 

You could sort-of fix this by prefixing your file name with the date/time..

 

Agree, but that's why I put that loop in there...

Also probably irrelevant but if you have an sql database, it's really easy to use a uniquely generated id for naming your images, everytime an image is uploaded, just add a new entry to your database, and wallah. a unique id. but since your doing it this way, you prolly not working with one?

Yes, I could put it some other ways, it's just annoying that it doesn't work as should.

Actually its purpose is to generate non-consecutive/non-pattern filenames as to make it hard to guess(not that anything bad happens if someone does). Again, just annoyed.

 

Thank you  :D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.