使用 PHP 检查 Zip 文件是否加密或受密码保护

Check if Zip file is encrypted or password protected using PHP

我正在编写一个扫描器,它可能会查找 hacked/malware 个文件。一项要求是使用某些 PHP 函数检查 zip(或任何压缩)文件是否受密码保护。

我不想添加任何额外的软件要求,所以应该在多台服务器上工作,使用 PHP 5.3+。 (是的,我知道 5.3 是旧的,但该过程可能需要 运行 在较旧的 PHP 安装上。)如果此检测在较新的 PHP 版本中可用,那么我可以编写代码将 运行 仅适用于较新的 PHP 版本。

我可以使用 file_get_contents() 函数将文件内容读入字符串。如何检查该字符串是否表明该 zip 文件受密码保护?请注意,我不想解压缩文件,只是检查它是否有密码保护。

谢谢。

此代码似乎有效,但可能会得到改进。

该过程似乎涉及两个步骤:

  • 使用zip_open打开文件,return正在获取资源。没有资源,zip打不开,可能是有密码

  • 使用zip_read读取zip中的文件。如果失败,则可能被密码

在这两种情况中的任何一种情况下,return 正确,表明 zip 文件中的密码可能。

// try to open a zip file; if it fails, probably password-protected
function check_zip_password($zip_file = '') {
    /*
    open/read a zip file
    return true if passworded
     */
    if (!$zip_file) { // file not specified
        return false;
    }
    $zip = zip_open($zip_file);     // open the file
    if (is_resource($zip)) {        // file opened OK
        $zipfile = zip_read($zip);  // try read of zip file contents
        if (!$zipfile) { // couldn't read inside, so passworded
            return true;
            } 
            else 
            { // file opened and read, so not passworded
            return false;
        }
    } else { // couldn't open the file, might be passworded
        return true;
    }
    return false; // file exists, but not password protected
}

请注意,代码仅确定无法访问 zip 中的文件,因此它们可能受密码保护。该代码不会尝试对 zip 内的文件进行任何处理。