【问题标题】:Check if zip or rar archive is empty or corrupted with Php检查 zip 或 rar 存档是否为空或使用 Php 损坏
【发布时间】:2018-12-26 11:31:09
【问题描述】:

我有一个非常简单的脚本,它只允许用户上传 .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']);

        }

【问题讨论】:

标签: php zip archive rar


【解决方案1】:

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)。

【讨论】:

  • 嘿,感谢这位罗比。所以我猜我需要遍历结果来单独检查所有文件?如果我想检查那里是否有 .exe 文件,我会检查 $za->filename?
  • 尽可能彻底。检查它是否打开就足以检查有效性,但如果你想添加额外的验证,你可以检查特定的文件/大小等。然后,您可以自定义错误消息“zip 显示无效”、“在 zip 中找不到文件 blah”、“zip 中的文件 blah 是空的”、“zip 中的文件 blah 不包含正确的数据”...。根据需要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
相关资源
最近更新 更多