1. Home
  2. /
  3. Web
  4. /
  5. How to zip files and folders on a server using PHP script?

How to zip files and folders on a server using PHP script?

How to zip files and folders on a server using PHP script

Introduction

Have you ever wondered how to zip a file on a linux server using PHP script. This is very useful in cases where you don’t have access to cpanel or whm.

This can be done by simply creating a PHP file on the root directory of domain and adding the following script in the php file. Once the script is added. Execute the script through a browser. Depending upon the file size the zip folder will be created with all files and directories/folders within minutes or seconds.

Steps to Zip files on the Server

1. Create a file “backup.php” on the root directory of the server

2. Add the following piece of script in backup.php

<?php 
$foldertobackup = 'yourfoldername';

$backup = '/home/xyz/public_html/'.$foldertobackup;

$newname = $foldertobackup.'.backup.zip';

$cmd = "zip -r $newname $backup";
                        
$compressFolder = exec($cmd ." 2>&1" );

echo $compressFolder;
                        
if($compressFolder)
{
	echo 'Done';
}else{
	echo 'Not Done';
}
?>

3. Now, open your web browser like chrome or firefox and run the backup.php file.

e.g. http://yourdomainname.com/backup.php

4. Within seconds or minutes… depending upon the file size the zip file will be created on your server.

5. Download the zip file using FTP.

How to know your directory path on the server?

Not sure, how to get the correct path of your root directory? Well, you can get it through dumping the $_SERVER variable. Use the var_dump($_SERVER); function in your script to know the detailed information.

Or, simply use the following:

$backup = $_SERVER['DOCUMENT_ROOT'] . '/' . $foldertobackup;

instead of the below piece of code

$backup = '/home/xyz/public_html/'.$foldertobackup;
Reviews & Ratings Get your stoe online with Shopify in 60 minutes Shop Now