24 November 2009

PHP: How to upload ZIP, check if file exists within it & extract to the server

I had to do this today for a job. It took far longer than it should have. The resources online are minimal and php.net does not mention any keywords like file_exists on manual for the function needed to do this. so...

Here is the best way to check if an uploaded zip archive contains a certain file and if so, extract the entire contents to a directory on your server:


Please see right hand panel before copying>

$zipFile=$_FILES["your file field name here"];
$checkFile="doesThisFileExist.html";
$exractPath="directory/to/extract/zip";

if($zipFile["error"] == UPLOAD_ERR_OK){
    if(strchr($zipFile['tmp_name'],'.zip')){
        $zip = new ZipArchive;
        $res = $zip->open($zipFile["tmp_name"]);
        if ($res === TRUE) {
            if(is_numeric($zip->locateName($checkFile))){
                $zip->extractTo($exractPath);
                //put extra functions here if you want
                $zip->close();
            }else{
                echo "ERROR: Uploaded zip archive is missing a required file!";
            }
        }else{
            echo "ERROR: Could not open uloaded zip archive";
        }
    }else{
        echo "ERROR: Uploaded file is not a zip archive"
    }
}else{
    echo  "ERROR: The upload was not successful";
}
Cron Design Studio: Dublin based web design & software development