|Renaming file before send to user?|
php file rename
| 2:08 pm on Jul 14, 2011 (gmt 0)|
This is probably a very simple and stupid question to ask, but I have no idea how I would go about doing this.
I am building some file hosting functionality for a client site in PHP. I have a central repository of files in one directory. This is because the client wants to maintain one copy of each file (based on the "hash" of the file) if multiple people upload the same file. Files are renamed before dumping them into this directory (datetime + some code) to avoid filename clashes. The original name(s) of the file are held on the database.
Where the problem is, is that I have no idea how I would go about renaming the file to the original filename when a user requests to download it? I could create a temporary copy of it in another directory, but I think this is going to get messy. I am hoping there is a better way. I have seen another post with Response.AppendHeader("content-disposition", "attachment; filename='MyFile.jpg'"); but that is in ASP.
Could anyone point me in the right direction?
| 2:19 pm on Jul 14, 2011 (gmt 0)|
That's exactly the header to use.
Let's say you know the original filename as $filename, and the path to the hashed copy as $hashed_filename, you could serve it with the original filename as follows:
header("Content-Disposition: attachment; filename=".$filename);
Remember that when sending header()'s your code must not have generated any output prior to that point...
| 4:41 pm on Jul 14, 2011 (gmt 0)|
|I have no idea how I would go about renaming the file to the original filename when a user requests to download it? |
Surely you are storing the "hash name" to keep track of it, correct? Then as said, you open "hashname" from the file system and when you output the headers, use "original filename" in the headers as demonstrated. No need to rename anything.
| 6:56 pm on Jul 14, 2011 (gmt 0)|
Users don't access "filenames". Filenames are internal implementation detail inside the server.
Users access URLs. URLs are a reference system used out there on the web. Publish the URL you want users to see and use in the links found on other pages, then rewrite that request once the link is clicked to fetch the actual content.
| 2:42 am on Jul 15, 2011 (gmt 0)|
Jesus, serious you guys. I have posted a lot of questions on a lot of forums, and I can honestly say I have not had such a thorough response before. Basically, you've answered the main question, and probably the next 3 questions I would ask :)
Rocknbill, yes I have the filenames stored, I just needed to know how to do the other things detailed here.
Thanks for your help guys and also thanks for writing in a clear and thorough way so I can understand. Much appreciated.