File Unzipper

File Unzipper
One of the PHP scripts I wrote that was actually put to actual use was the File Unzipper. As the word, it unzips zip files using PHP. Modern Windows operating systems has built-in functionality that allows you to unzip zip files. Back in the past, you have to use an application such as WinZip or Winrar to unzip them. PHP has that same capability, and this is what I am going to demonstrate in this post.

The one I made for a company was designed for an autofetch function. It fetches the file from a url, and since this file is in zip format, PHP has to do an additional function that unzips the file. Here, I am going to do a similar function and tweak it a little to enable it to extract not only zip files but rar files as well.

In order for this PHP file to work, you need to configure your web server (ie. XAMPP) to enable Rar support. Rar Archive functions are dependent on PEAR (PHP Extension and Application Repository) — a framework and distribution system for reusable PHP components. So, you need to have this installed along with a php_rar.dll file from PECL. Then, have php.ini configured (see how to configure it on XAMPP).

If everything is setup properly, you may download my PHP code from my Google Drive.

Download File Unzipper

File Unzipper [Google Drive]

Once downloaded, unzip it in htdocs (assuming you’re using XAMPP) or www in WAMP. Make sure that the uploads folder is in the same folder as with the file_unzipper.php file, otherwise, you’ll get an error — That is since some of my variables target this folder for uploading purposes.

The Code

I will only be explaining some new codes I didn’t mention in my previous PHP projects. You guys may have to find out the rest of the codes that I used. For this one, I will only be focusing on Zip and Rar functions.

Please see the comments in the code for a brief explanation.

<?php
//systemp.php can be found in \xampp\php\pear\. It is a PHP file use for File/Directory Manipulation. We are including this because this is one way to determine if PEAR is installed or not.
require_once 'System.php';

if(!isset($_POST['submit'])){
	$upload_form = '<form method="POST" enctype="multipart/form-data">
	  Select a file to upload:
	  <input type="file" name="fileToUpload" id="fileToUpload">
	  <input type="submit" value="Upload" name="submit">
		</form><br><br>';
} else {
	$upload_form = '';
}
?>
<html>
<head>
	<title>File Unzipper</title>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<style>
		body{
			background-color:#744021;
			font-family: Helvetica Neue, arial;
			color:#fff;
		}

		h1 {
			font-size: 18px;
		}
	</style>
</head>
<body>
<h1>File Unzipper</h1>
This PHP file will decompress compressed zip or rar files and save their contents in the folder of your choice.<br><br>
<?php
	error_reporting(0);
	$form_upload = '<form method="POST" enctype="multipart/form-data">
	  Select a file to upload:
	  <input type="file" name="fileToUpload" id="fileToUpload">
	  <input type="submit" value="Upload" name="submit">
		</form><br><br>';
	echo $upload_form;
	set_time_limit(1500);
	$target_directory = 'uploads/';

//We are using an array for these variables.
	$zip_mime_types = array(
		'zip' => 'application/x-zip-compressed','multipart/x-zip','application/x-compressed','application/zip'
	);
	$rar_mime_types = array(
		'rar' => 'application/x-rar-compressed', 'application/octet-stream', 'application/x-rar'
	);

	if(isset($_POST['submit'])){

//May be required to clear the cache. To make sure that every uploaded file is new.
		clearstatcache();

//basename - Returns trailing name component of path [PHP Manual]. $_FILES is a superglobal variable that contains the uploaded file. The first bracketed variable contains the variable name for the uploaded file while ['name'] is meant to contain the uploaded file from the browser.
		$file = $target_directory . basename($_FILES['fileToUpload']['name']);

//strtolower stands for string to lower case. As the name, it converts strings to lower case. pathinfo returns information about a file path, PATHINFO_EXTENSION is the attribute for pathinfo, it means get file extension of the file.
		$filetype = strtolower(pathinfo($file,PATHINFO_EXTENSION));

// First layer check. To make sure that file type is zip or rar.
		if($filetype == 'zip' || $filetype == 'rar'){

//finfo(FILEINFO_MIME_TYPE) gets the Mime Type of the file.
			$fileInfo = new finfo(FILEINFO_MIME_TYPE);

//This part of the code tells PHP to apply finfo function to $_FILES['fileToUpload']['tmp_name']. ['tmp_name'] refers to the uploaded file that has now been transferred into your temp folder. As to where, it depends on your config settings, but the user has no control, so this isn't tainted.
			$mimed = $fileInfo->file($_FILES['fileToUpload']['tmp_name']);

//in_array searches the array variable and returns a boolean of True or False, depends if it finds the searched string or not.
			$file_extension = in_array($mimed, $zip_mime_types, TRUE);
			$file_ext = in_array($mimed, $rar_mime_types, TRUE);
			$tmp_file = $_FILES['fileToUpload']['tmp_name'];

//This variable is a left-over from the previous code before I revised it. It was meant to get the header information.
			$bytes = file_get_contents($tmp_file, FALSE, NULL, 0, 7);

// Second Layer check. Mime check.
			if($filetype == 'zip' && $file_extension == 'zip'){

// Third layer check. Strict check. I disabled it because this only works for files with mime type application/zip and application/x-rar
//			if(substr($bytes, 0, 2) == 'PK'){

//Initiate ZipArchive functions. Object-oriented method.
				$zip_file = new ZipArchive;

//Opens zip file.
				$res = $zip_file->open($tmp_file);

//If it manages to read...
				if($res === TRUE){

//exTractTo as the word means extract the content of the zip file to this directory. OR die means that if this method fails, then display this message instead.
					$zip_file->extractTo($target_directory) OR die($form_upload . 'Zip file might be password protected! Unable to extract!');

//Closes the zip file.
					$zip_file->close();
					echo 'Successful! Zip file extracted! Check uploads folder..<br><br>
						<a href="file_unzipper.php"><button type="button">Upload Another</button></a>';
				} else {
					echo $form_upload;
					echo 'Unable to extract Zip File! Please check your file to make sure it\'s a valid zip file.';
				}
			} else if($filetype == 'rar' && $file_extension == 'zip'){
				echo $form_upload;
				echo 'The extension is .rar but the mime type is ' . $mimed;
			} else if($filetype == 'zip' && $file_ext == 'rar'){
				echo $form_upload;
				echo 'The extension is .zip but the mime type is ' . $mimed;
			} else if($filetype == 'rar' && $file_ext == 'rar'){

//This is supposed to be a strict check for Rar, but for the same reason as zip, I removed it because it only applies to files with mime type - application/x-rar.
//			if(bin2hex($bytes) == '526172211a0700'){

//This check checks if PEAR is installed. This is necessary to avoid PHP from crashing if PEAR is not installed.
				if(class_exists('System') == FALSE){
					echo $form_upload . 'Rar function cannot run without PEAR. Please install PEAR and activate Rar Support first!';
				} else {

//rar_open opens a Rar Archive file.
					$rar_file = rar_open($tmp_file) OR die ($form_upload . 'Unable to extract Rar File! Please check your file to make sure it\'s a valid rar file. Also make sure that PEAR is installed and PHP is configured to support Rar functions!');

//Unlike zip, Rar needs a list of the files inside the Rar file. rar_list is use to retrieve it. But before it can, the rar file has to be opened first.
					$rar_entry = rar_list($rar_file);

//Once list is retrieved. We can use it to guide PHP in finding out which files will be extracted from the Rar file.
					foreach($rar_entry as $entry){
						$entry->extract($target_directory) OR die($form_upload . 'Rar file might be password protected! Unable to extract!');
					}

//rar_close closes the rar file.
					rar_close($rar_file);
					echo 'Successful! Rar file extracted! Check uploads folder..<br><br>
						<a href="file_unzipper.php"><button type="button">Upload Another</button></a>';
				}
			} else {
				echo $form_upload;
				echo 'Invalid File Format<br>';

//This throws a PHP error message.
//				throw new RuntimeException('Invalid File Format');
			}
		} else {
			echo $form_upload;
			echo 'The File Extension is neither a zip or a rar!';
		}
	}
?>
</body>
</html>

So that’s it. Feel free to share it and please do provide a link back. Those link backs will be greatly appreciated. If you guys have questions, please drop me a comment.

Follow me at:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.