简体   繁体   English

使用Php检查zip或rar存档是空的还是已损坏

[英]Check if zip or rar archive is empty or corrupted with Php

I have a very simple script that allows user to upload only .zip or .rar files. 我有一个非常简单的脚本,允许用户只上传.zip或.rar文件。 I'd like to know how do I know if a file is corrupted or empty? 我想知道如何知道文件是否已损坏或为空?

This my script 这是我的剧本

if(isset($_POST['customerid']) && $_FILES['file']['tmp_name'] && $_POST['requestid']){

            //post variables
            $customerid = $_POST['customerid'];
            $filename = $_FILES['file']['name'];
            $requestid = $_POST['requestid'];

            //check if the file is .rar or .zip
            $fileInfo = new finfo(FILEINFO_MIME_TYPE);
            $fileMime = $fileInfo->file($_FILES['file']['tmp_name']);
            $validMimes = array( 
              'zip' => 'application/zip',
              'rar' => 'application/x-rar',
            );

            $fileExt = array_search($fileMime, $validMimes, true);
            if($fileExt != 'zip' && $fileExt != 'rar'){

                echo 'Not a zip or rar.';
            }

            //check if the file is corrupted or empty


            //if all OK insert file name and path to database
            $uservalida_stmt = $conn->prepare("INSERT INTO user_project_files (dateCreated,userid,projectFile,serviceRequestId) VALUES (?,?,?,?)");
            $uservalida_stmt ->bind_param('siss',$currentdate,$customerid,$filename,$requestid);
            $uservalida_stmt ->execute();
            $uservalida_stmt ->close();

            //move upload and EXTRACT file to directory
            move_uploaded_file($_FILES['file']['tmp_name'], '../user/project/' . $_FILES['file']['name']);

        }

The PHP manual has examples for zip. PHP手册有zip的例子。 http://php.net/manual/en/zip.examples.php http://php.net/manual/en/zip.examples.php

<?php
$za = new ZipArchive();

$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status  . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";

echo "numFile:" . $za->numFiles . "\n";
?>

or check the error codes simply on the open function ( http://php.net/manual/en/ziparchive.open.php ) 或者只是在open函数上查看错误代码( http://php.net/manual/en/ziparchive.open.php


You can also do similar with RAR files ( http://php.net/manual/en/rararchive.open.php ) but will need to install it first ( http://php.net/manual/en/rar.installation.php ). 您也可以使用RAR文件( http://php.net/manual/en/rararchive.open.php )进行类似操作,但需要先安装它( http://php.net/manual/en/rar.installation .php )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM