Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename pdf file to be downloaded on fly

Tags:

file

php

rename

Given: All the uploaded pdf files on server are prefixed with timestamps. Later user can download these files again. These (ugly)filenames would never change again on server.

Question: When I give the option to download PDF file, name of the file looks ugly and lengthy. How can I change this name to something sensible, so that when user downloads this file, name doesn't look weird?

Do I need to make a copy, since renaming the original file is not an option? Wouldn't it be extra overhead for each downloadable file? Obviously deleting the copied file would be another extra step?

Is it possible to rename file once file is completely downloaded on client side?

What do you guys suggest?

like image 558
understack Avatar asked Dec 03 '22 14:12

understack


2 Answers

Something like this:

<?php
// We'll be outputting a PDF  
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');
?> 
like image 122
Klaus Byskov Pedersen Avatar answered Dec 20 '22 16:12

Klaus Byskov Pedersen


I needed to do this for a recent project and was a bit confused on how to implement, but figured it out shortly after seeing Klaus's answer. To further elaborate on Klaus' response:

1) Create a file called, say, "process.php". Modify Klaus's code so that it accepts two parameters: the original filename and the new name. My process.php looks like:

<?php
$file = $_GET['file'];
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename='.$_GET['newFile']);
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

2) Create a link on your user-facing page that points to the processor script:

<a href="process.php?file=OriginalFile.pdf&newFile=MyRenamedFile.pdf">DOWNLOAD ME</a>
like image 43
zombiedoctor Avatar answered Dec 20 '22 17:12

zombiedoctor