<?php

	include 'functions.php';

if(isset($_FILES['fupload'])) {
	$filename = $_FILES['fupload']['name'];
	$source = $_FILES['fupload']['tmp_name'];
	$type = $_FILES['fupload']['type'];
	
	$name = explode('.', $filename); # $name[0] returns the name of the file. $name[1] returns the extension (zip)
	$target = 'extracted/' . $name[0] . '-' . time() . '/';  # Where the file will be saved. I.E. 'extracted/myFile-02151985/'
	
	// Ensures that the correct file type was chosen.
	$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
	foreach($accepted_types as $mime_type) {
		if($mime_type == $type) {
			$okay = true;
			break;
		} 
	}
	
	// Safari/Chrome don't register zip mime types. Something better could be used here - with the use of the PEAR extension.
	$okay = strtolower($name[1]) == 'zip' ? true : false;

	if(!$okay) {
		die("Please choose a zip file, dummy!");
	}

	#$unique_folder = $name[0] . '-' . time() . '/';
	mkdir($target);
	$saved_file_location = $target . $filename;
	
	if(move_uploaded_file($source, $target . $filename)) {
		openZip($saved_file_location);
	} else {
		die("There was a problem");
	}
	
	$scan = scandir($target . $name[0]);
	
	print '<ul>';
	for($i = 0; $i<count($scan); $i++) {
		if (strlen($scan[$i]) >= 3) { # $scan[$i] is equal to the file name for each iteration.
			$check_for_html_doc = strpos($scan[$i], '.html');
			$check_for_php = strpos($scan[$i], '.php');
			if ($check_for_html_doc === false && $check_for_php === false){
				echo '<li>' . $scan[$i] . '</li>';
			} else {
				echo '<li><a href="' . $target .  $name[0] . '/' . $scan[$i] . '">' . $scan[$i] . '</a>';
			}
		}	
	}
	print '</ul>';
} 

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html>
  <head>
    <title>How to Upload and Open Zip Files With PHP</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
        <link rel="stylesheet" href="css/default.css" />

  </head>
  <body>
    <div id="container">
	<h1>Upload A Zip File</h1>
	<form enctype="multipart/form-data" action="" method="post">
		<input type="file" name="fupload" /><br />
		<input type="submit" value="Upload Zip File" />
	</form>

    </div>
  </body>
</html>
