Reputation: 69
I have made a web site with PHP and I have to download a file from FTP server.
I don't want to save temporarily the file on the web server, so I save it in the PHP buffer. But when I download it, the buffer apparently is empty because the filename matches but the file is empty.
Here's my code
ob_start();
ftp_chdir($conn_id, $_REQUEST["path"]);
ftp_get($conn_id, "php://output", $_REQUEST["remoteFile"], FTP_BINARY);
$data = ob_get_contents();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='. $_REQUEST["remoteFile"]);
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($data));
echo $data;
ob_end_clean();
exit;
For example, when I try to download a txt file, previously rightly uploaded, the filename is ok but content is empty.
Upvotes: 2
Views: 1334
Reputation: 202272
At the point you are calling the echo $data;
, the output buffering is still on. So you write the data back (second time) to the output buffer. And then you clear it. So nothing is outputted.
Just revert the echo $data;
and ob_end_clean();
calls:
ob_end_clean();
echo $data;
Though a way easier is to do something like:
$data = file_get_contents("ftp://username:[email protected]/path/file.dat");
header(...);
echo $data;
Assuming ftp:// protocol wrappers are enabled.
And you do not need any buffering. And you also won't have the file twice in the memory at any point.
For even better implementation with Content-Length
header, see:
Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server
Upvotes: 2