简体   繁体   中英

PHP Pass File Handle to user so that file downloads & saves to their machine

I am downloading a file from another server. I wish to push this file to my users rather than saving it to my server.

In other words, pass them the file handle so it just passes through my server and saves to their machine. How can I do this? I have this so far:

$handle = fopen($_GET['fileURL'], 'r');
$filename = stream_get_contents($handle);

How do I push this to the user, maybe using headers?

Thank you for any help and direction.

EDIT

I have the headers:

header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");

Its just that it doesn't push the headers. I just get a blank page after about 15 seconds which looks like it downloading the file but not giving it to me.

I wish for the script to immediately send the headers to the user as a stream. exit();

You can try this

$filetype = mime_content_type($filename);
header('Content-type: '.$filetype);
header('Content-Disposition: attachment; filename="'.$filename.'"');

UPDATE for your EDIT:

Do you have errors disabled, since this sounds like the headers already sent error?

error_reporting(E_ALL | E_STRICT);

You don't have to use fopen() when using readfile();

Just include the filename inside readfile() like this:

readfile($_GET['fileUrl']);

Although this is very dangerous security-wise as the user could specify any file on your file server. If you only have a few files you want someone to be able to download perhaps you should store them in an array (or database, preferebly)

Here's an array example:

$files = array('file1.jpg', 'file2.png', 'file3.pdf');
//assume $_GET['file_id'] == 0, 1 or 2

if (file_exists($files[$_GET['file_id']]))
    readfile($files[$_GET['file_id']]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM