Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming files when downloading it

Tags:

php

I want to rename file when user downloads it.

Right now, I'm sending content-disposition and content-length headers and then send file to user with fpassthru PHP function.

But there is 3 problems with this method:

  1. If I'm sending big (above 3-4Gb) files this way, then my PHP script runs too much time and may be killed by timeout.
  2. If user cancels the download, PHP script continue to read and send the file
  3. If user pauses the download, he cannot resume it later.

Is there any nicer way to rename files on download?

like image 473
Boffin Avatar asked Nov 26 '09 01:11

Boffin


2 Answers

Since the question was asked, some time has gone by and html5 gave us a different approach to this:

<a href="someWeiredFileName.rar" download="coolFilename.rar">Download</a>

The attribute download (learn more) defines the default filename for storing the file on the clients computer (he'll still be able to change it!).

Note: this won't affect anything on your server.

like image 142
RienNeVaPlu͢s Avatar answered Oct 18 '22 04:10

RienNeVaPlu͢s


<?php
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?> 
  1. The file will be offered for download as "downloaded.pdf" while its original name was "original.pdf".

Pseudo code

while(1) {
    Echo "..."; //<-- send this to the client
    if (connection_status()!=0){
    die;
    }
}
  1. You can stop the PHP script if a user cancels the browser by using connection_status()

  2. HTTP can not reconnect a closed connection. FTP can!

like image 31
powtac Avatar answered Oct 18 '22 03:10

powtac