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
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.

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.