Force download a file with PHP Print

  • pdf files, force download
  • 2

This is a super helpful script if you need to force download a PHP file from another location on the server.

In the example below, we have a pdf file located in an htaccess password-protected directory at /home/jucra/public_html/kb/downloads/JUCRA-Digital-Agency-Rate-Card.pdf but we still want to allow users to download the pdf file from the front end.

So when we send someone to download the file from https://www.jucra.com/downloads/ratecard/ it will actually download the pdf file from another part of the server.

It means that when we update the file in the private repo, the public will also have access to the same copy without us having to upload two versions.

###########################
// force download a file
// see: https://www.jucra.com/whmcs/knowledgebase/171/
###########################
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
$file_path = "$root/kb/downloads/jucra-sales-brochures/JUCRA-Digital-Agency-Rate-Card.pdf";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
flush();
readfile($file_path);
exit;

Was this answer helpful?

« Back