Tag Archives: Extract

Extracting a Zip file with PHP

I recently had to make a quick script to extract the contents of a zip file, this zip file is copied via ftp from a remote server and stored locally. The file name to request and transfer is set via URL Encoding. This were originally a function, which I converted into a class and now devolved totally for this small script.

Sometimes quick and dirty tasks, require quick and dirty code, using the class would have been overkill. As usual there are a dozen ways to do this, and you could remove the error checks and echo’s to make the code even more compact.

// get the absolute path to $file ($file is set via the transfer process, but is JUST the file name no extension).
$path = pathinfo(realpath($file.'.zip'), PATHINFO_DIRNAME);
$link = $path.'/'.$file.'.zip';
$linkz = $path.'/'.$file.'.csv';
// assuming file.zip is in the same directory as the executing script.
	if (file_exists($linkz)) {
		die("<p>The .csv file exists, exit processs.</p>");
		echo "<p>The $link exists, and $linkz file doesn't exist.</p>";		
		//prepare for handling a zip file.
		$zip = new ZipArchive; 
		// load the zip file.
		$res = $zip->open($file.'.zip');
		if ($res === TRUE) { // check the file has been loaded.
			echo "<p>Extracting File...</p>";
			$zip->extractTo($path); //begin extracting file
			$zip->close(); //unloa and release the zip file.
			echo "<p>$file.zip extracted to $path</p>";
		} else {
			echo "<p>Doh!, stupid $file.zip wouldn't open.</p>";

		die("<p>$file.zip doesn't exist, exit process.</p>");


Its a little messy, but were procedural code, converted into a function, then part of a class and back to a procedural layout.