Download Zip Files Dynamically in PHP

PHP

Read {count} times since 2020

Zip file downloading is used by websites. The most important and popular of them is WordPress. They use Zip files for downloading plugins, themes and even their versions. They do it ofcourse, dynamically. You just provide the location of the file and PHP will download it to the user for you. Actually HTTP headers have the main role in the downloading.

We make the headers using header function in PHP and the browser will take care of the rest. The file path that you provide must be the absolute path. These are the two variables where you provide information about the Zip file :

$filename = "My Zip File Download.zip";
$filepath = "/var/www/subinsbdotcom/download_cdn/file.zip";

The download file name is stored in the $filename variable and the file location is in the $filepath variable.

Now we’re going to set the headers for making browser understand that this should be downloaded :

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath));
ob_end_flush();
@readfile($filepath);

When the user visits the page, the download will start. The downloaded file will be of the name My Zip File Download.zip. You can change the name by changing the value of $filename.

Show Comments