Search code examples
phpzend-frameworkfile-uploadzend-file

PHP: Storing file locations...what if overwritten?


I am currently using the Zend Framework and have an upload file form. An authenticated user has the ability to upload a file, which will be stored in a directory in the application, and the location stored in the database. That way it can be displayed as a file that can be downloaded.

<a href="/upload-location/filename.pdf">Download</a>

But something I am noticing is that a file with the same name will overwrite a file in the uploads directory. There is no error message, nor does the filename increment. So I think the file must be overwritten (or never uploaded).

What are some best practices I should be aware of when uploading, moving, or storing these files? Should I always be renaming the files so that the filename is always unique?


Solution

  • Generally, we don't store files with the name given by the user, but using a name that we (i.e. our application) chosse.

    For instance, if a user uploads my_file.pdf, we would :

    • store a line in the DB, containing :
      • id ; an autoincrement, the primary key -- "123", for instance
      • the name given by the user ; so we can send the right name when someone tries to download the file
      • the content-type of the file ; application/pdf or something like that, for instance.
      • "our" name : file-123 for instance
    • when there is a request to the file with id=123, we know which physical file should be fetched ('file-' . $id) and sent.
    • and we can set some header to send to correct "logical" name to the browser, using the name we stored in the DB, for the "save as" dialog box
    • same for the content-type, btw

    This way, we make sure :

    • that no file has any "wrong" name, as we are the ones choosing it, and not the client
    • that there is no overwritting : as our filenames include the primary key of our table, those file names are unique