How to force download file in WordPress

Here is piece of code for how to force download file in WordPress

$file = $download['link']; //this is url of file - http://yoursitename.com/.../.../yourfile

$file_location = $_SERVER['DOCUMENT_ROOT'] . substr($file, strpos($file, '/wp-content')); // this is real path /var/www/....

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_location));
readfile($file_location);
exit();

 

 

Leave a Reply