Download PDF from FTP server, and save directly to client machine - PHP

Asked

Viewed 346 times

2

I’ve been trying to solve this problem for a few days!

I need to download some pdf’s that are on the FTP server right in the client’s browser, but when I do this by forcing headers, the file even downloads but corrupted "Failed to load PDF document."

Follow the code below:

$ftp_arquivo = "path/arquivo.pdf";
$ftp_host = "ftp.exemplo.com.br";
$ftp_port = "21";
$ftp_username = "usuario";
$ftp_senha = "senha";


ob_start();

$fcon = ftp_connect($ftp_host);
$conecta = ftp_login($fcon, $ftp_username, $ftp_senha);
ftp_pasv($fcon, true);

$arquivo = basename($ftp_arquivo);

ftp_get($fcon, $arquivo, $arquivo, FTP_BINARY); 

ftp_close($fcon);


$file = $arquivo;

$size = filesize($arquivo);

header("Content-Description: File Transfer");
header("Content-type:application/octet-stream");
header("Content-Length: {$size}");
header("Content-Disposition: attachment; filename=\"" . $file . "\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

ob_clean();
flush();
  • Julia, does the folder in the destination exist? Something else, wouldn’t it be better to give a ftp_chdir($fcon, $path); to enter the folder where the file is?

  • Rodrigo, I added ftp_chdir($fcon, $path); and I even added an echo to see if it was in the correct directory, and it is! There is the possibility of the error being at the time I do ftp_get and then pass pro header?!

  • I tried several things here Julia, but unsuccessfully too... I changed the Content-type for application/pdf When starting the download it recognizes my example pdf file with the size of 1MB, however it downloads something else of 1Kb... I’d like to see more people helping you because it interests me to know too!

  • Shouldn’t have a echo file_get_contents($arquivo); to download?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.