检查zip或rar档案是否为空或是否被Php损坏

时间:2018-07-18 13:52:01

标签: php zip archive rar

我有一个非常简单的脚本,该脚本只允许用户上载.zip或.rar文件。我想知道如何知道文件已损坏或为空?

这是我的脚本

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']);

        }

1 个答案:

答案 0 :(得分:3)

PHP手册提供了zip示例。 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";
?>

或仅通过open函数(http://php.net/manual/en/ziparchive.open.php)检查错误代码


您也可以对RAR文件(http://php.net/manual/en/rararchive.open.php)执行类似操作,但需要先安装(http://php.net/manual/en/rar.installation.php)。