This PHP script provides a utility function to zip a folder and its contents. It utilizes the ZipArchive class in PHP to create a zip file from a specified source folder.
- PHP version 5.2 or higher.
- The
zip
extension must be enabled in your PHP configuration.
- Ensure that the PHP version on your server is compatible.
- Make sure the
zip
extension is enabled in your PHP configuration. - Adjust the
$sourceFolder
and$destinationZip
variables to the appropriate paths in the script. - Optionally, modify the exclusion condition in the loop to omit specific folders or files from being zipped.
- Save the provided PHP code into a
.php
file, for example,zipper.php
. - Open a terminal or command prompt.
- Navigate to the directory containing
zipper.php
. - Run the script using the PHP interpreter:
php zipper.php
- Include the
zipFolder
function in your PHP project. - Set the
$sourceFolder
variable to the path of the folder you want to zip. - Set the
$destinationZip
variable to the desired location and name of the zip file to be created. - Execute the script to zip the folder.
- Adjust the exclusion condition in the loop to omit specific folders or files from being zipped, if needed.
// Change the Source Path
$sourceFolder = './';
$destinationZip = './archive.zip';
if (zipFolder($sourceFolder, $destinationZip)) {
echo 'Folder zipped successfully!';
} else {
echo 'Failed to zip folder.';
}
To execute the script:
-
Make sure the script is saved with a
.php
extension (e.g.,zip_folder.php
). -
Upload the script to your server or run it locally.
-
Access the script through a web browser or execute it via the command line. After executing the script, you should see one of the following outputs:
-
If the folder is zipped successfully, it will display
Folder zipped successfully!
.- If successful, the script will create a zip file containing the contents of the specified folder.
-
If there's an error during zipping, it will display
Failed to zip folder.
along with any error messages encountered.