How to create a zip file in PHP


I will show you how to create a zip file in PHP. All the directory in your server will also be zipped in the code. I will use the ZipArchive class in php. It’s easy as 1 2 3 :)

function ListFiles($dir) {
	if($dh = opendir($dir)) {
		$files = Array();
		$inner_files = Array();
		while($file = readdir($dh)) {
			if($file != "." && $file != ".." && $file[0] != '.') {
				if( $dir == getcwd() )	continue;
				if(is_dir($dir . "/" . $file)) {
					$inner_files = ListFiles($dir . "/" . $file);
					if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
				} else {
					array_push($files, $dir . "/" . $file);

		return $files;

$zip = new ZipArchive();
$backupName = date("Y-M-d-h:i:a",time());
$filename = $backupName.".zip";
#Store the backup file in a Folder called 'Files'
if( $zip->open("Files/".$filename,ZIPARCHIVE::CREATE) !== TRUE ) {
	exit("Cannot open the archive file");
#Replace this one with your root directory
$directory = '/home/mysite/public_html';
foreach (ListFiles($directory) as $key=>$file){
        #do not include the backup files to be backed-up 
	if( strstr($file,getcwd()) != "" ) continue; 

To download the zip file, just access it through your browser, so mine is I put the zip file in a File Directory, so it should be something like this: . It really depends.

Hope this helps someone! Have a happy coding!

Advance File Upload in PHP

I’ll show you a so called advance file upload implementation in PHP.
Advance because we’ll be changing the file name of the uploaded file for some good reason. I’m sure you’re thinking why should we change the file name of the uploaded file. The reason for that is that every time we’ll upload a file, we are going to store it in our server.

So what happens now if the file name already exist in the server? PHP will automatically replace the file without letting us now, so it’s kinda weird.

Think of it this way:
User1 uploads a file called “document.doc“. Then, User2 uploads a file called “document.doc”(same file name with User1). Of course those 2 files have different content in it, they just have the same file name. PHP replaces the file of User1 into the file that was uploaded by User2. So now, you got my point. :)

Here’s what we’re going to do.

<form action="upload.php" method="post" enctype="multipart/form-data">
if( $_SESSION['img_upload_error'] ) echo $_SESSION['img_upload_error'];
     <label for="uploadImage">Upload Profile Picture</label>
     <input id="file" type="file" name="file" />
     <input type="submit" />
unset( $_SESSION['img_upload_error'] );


$file = $_FILES['file'];
#this is a function that will get the file extension of the uploaded file
 $file_extension = GetFileExtension( $file['name'] );

#we will change the name of the file name at the same time we'll append the file extension
$fileName = GenerateRandomStringAndInt().".".$file_extension;

if ( $file["error"] > 0 ) #If there's an error, return back to the previous page
   $_SESSION['img_upload_error'] = "There was an error while uploading your image. Please try again";
   header( "location: ".$_SERVER['HTTP_REFERER'] ); #this would redirect user to the previous page
     #1MB, We are limiting the file upload into 1MB you can always change this one depending on your  preference.
     if( $file['size'] > 1024000 ) 
        $_SESSION['img_upload_error'] = "There was an error while uploading your image. Please try again";
        header( "location: ".$_SERVER['HTTP_REFERER'] );

     #while the file is exsting in the server, replace the filename
     while( file_exists( "/files/" . $fileName ) ) #/files/ is the directory where we will store the files
        $fileName = GenerateRandomStringAndInt().$file_extension;

       move_uploaded_file( $file["tmp_name"], "/files/" . $fileName );

function GetFileExtension( $filename )
   return pathinfo( $filename, PATHINFO_EXTENSION );

function GenerateRandomStringAndInt( $length = 15 )
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string ="";
    for ( $p = 0; $p < $length; $p++ ) {
        $string .= $characters[ mt_rand( 0, strlen( $characters ) ) ];
    return $string;

Now you are golden! Just create a directory named  “files” so that we’ll store the files in there.

This is how easy to implement an Advance File Upload in PHP.

Hope this helps someone.

Have a happy coding! :)