Wordpress readfile() function download zip file error: An Error occurred while loading the archive

I worked for 1 day to solve this problem. This issue encounter in the WordPress system. Here is the use-case:

We have a zip file and we want to downloadable links for users. I see a lot of examples and tried many of them. But I couldn’t solve this issue. I wanted to write this solution for people like me.

Here is the solution:

$fileName = “download.zip”;
$filePath = “/home/antmedia.io/public_html/wp-content/uploads/” . $fileName;
header(‘Pragma: public’);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Expires: 0”);
header(“Content-Type: application/zip”);
header(“Content-Disposition:attachment; filename={$fileName}”);
header(“Content-Type: application/force-download”);
header(“Content-Transfer-Encoding: binary”);
while (ob_get_level()) {
ob_end_clean();
ob_clean();
flush();
}

readfile(“$filePath”);
exit();

I hope, it works for you :)

Written by

Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store