views:

83

answers:

2

How can I use PHP's include function to include a file and then modify the headers so it forces - at least that's how it's called - browsers to download ITSELF (the PHP file). Is it possible to also modify the preset save name, in order to change the extension from *.php to something else?

Thanks in advance!

+5  A: 

PHP include function will parse the file. What you want to do is use file_get_contents or readfile.

Here's an example from the readfile documentation:

$file = 'somefile.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

Change the headers to suit your particular needs. Check out the above links for more info.

webbiedave
OK. Thanks for that one! But how can I then download the file, anyway? Or even force the download?
arik-so
with: echo file_get_contents('source_of_file');
rubber boots
How can I use file_get_contents with subfolders? It just won't work :(
arik-so
Try using an absolute path. For more flexibility, you can prepend a relative path with $_SERVER['DOCUMENT_ROOT'].
webbiedave
Thanks a lot! Worked well, more or less - but I have another solution. Which I will share, naturally!
arik-so
A: 
<?php

$wishedFileName = 'myNewFile.txt';

header("Content-Disposition: attachment; filename=\"" . $wishedFileName . "\"");
header("Content-Type: application/force-download");
header("Connection: close");

echo file_get_contents('one/location/nobody/could/ever/guess/noteventhefilename.txt');

?>

That's how I've done it. That way, the content is printed into the file, but not seen by the user, because it has to be downloaded.

arik-so

arik-so