Chibuzo
Chibuzo

Reputation: 6117

How to generate unique filenames for uploaded pictures

I store uploaded pictures in a folder while I store the path and filename in a database. Please how best can I generate unique filenames to avoid name conflict in the folder? Thanks

Upvotes: 1

Views: 1875

Answers (4)

Kevin Burton
Kevin Burton

Reputation: 11936

Have you considered storing the data in the database ?

If you are able to; you will get rid of the need to have unique file name, and the problems associated with the files & database being out of synch.

Upvotes: 0

omnath
omnath

Reputation: 509

You can use

$image_name=('Your folder path/'. time () .'.'$extension);

for get any image extension

 $extension = getExtension($filename);

    function getExtension($str) {
     $i = strrpos($str,".");
     if (!$i) { return ""; }
     $l = strlen($str) - $i;
     $ext = substr($str,$i+1,$l);
     return $ext;

}

is little complex but its make your work easy , you can use this extension for validation on your file type like

   if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") &&     ($extension != "gif")) 
    {
        echo '<h1>Unknown extension!</h1>';
        $errors=1;
    }else
             //your code to save image in folder.

Upvotes: 0

George
George

Reputation: 479

Probably the closest unique value you have is the database file ID. But if you save your files in different tables this will no longer be the case (ex: ArticleFiles and NewsFiles tables). In this case you can use separate directories for separate tables, or prefixing your files.

You may also be required to upload files to the same server location from different host names. In this case you can prefix the file name with the host name used for upload.

People tend o use the time() function, but that's mostly informative, as it doesn't protect you against concurrent uploads. It does help you in finding the files on the disk easier, by ordering. For the same reason you may include the original extension in the file name.

In the end, use the shortest and most informative unique value or composed value you can get, like

$file = "{$HOST}.{$TYPE}.{$TIMESTAMP}.{$DATAID}.{$EXT}.uploaded";

However, be very careful with access rights on your uploads folder, as it's a serious security risk. Do not allow execution rights, try placing it outside of the document root, check uploads for possible dangerous files, etc.

Upvotes: 3

TehShrike
TehShrike

Reputation: 10074

You've tagged your question with PHP and MySQL.

  • You could use PHP's uniqid function to generate a unique string
  • You could use a MySQL table to store information about the images, and use an AUTO_INCREMENT key in that table to give you a unique integer which you could use as the file name

Do you have any more specific requirements/goals? If not, I imagine either of those solutions should work for you.

Upvotes: 7

Related Questions