Upload and unzip files in PHP

0

I have this snippet of code to upload and decompress zip files on the server and it works. I have two doubts, in principle it is only to upload zip files but it is assumed that if you try to upload something else it will give the message that only zip files are allowed and it only does that before the message gives an error, the second is that if there is way to modify it to upload any file but if it detects a zip that unzips it. Thanks in advance, this is the fragment in question.

<?php
if($_FILES["zip_file"]["name"]) {
    $filename = $_FILES["zip_file"]["name"];
    $source = $_FILES["zip_file"]["tmp_name"];
    $type = $_FILES["zip_file"]["type"];

    $name = explode(".", $filename);
    $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;
        } 
    }

    $continue = strtolower($name[1]) == 'zip' ? true : false;
    if(!$continue) {
        $message = "The file you are trying to upload is not a .zip file. Please try again.";
    }

    $target_path = ".".$filename;  // change this to the correct site path
    if(move_uploaded_file($source, $target_path)) {
        $zip = new ZipArchive();
        $x = $zip->open($target_path);
        if ($x === true) {
            $zip->extractTo("/uploads/"); // change this to the correct site path
            $zip->close();

            unlink($target_path);
        }
        $message = "Your .zip file was uploaded and unpacked.";
    } else {    
        $message = "There was a problem with the upload. Please try again.";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
    
asked by Shoropio 16.09.2018 в 18:38
source

0 answers