clamav_ClamAV作为Zend Framework中的验证过滤器

clamav

Ok, so you’re pretty comfortable with using the Zend Framework, specifically the use of Forms. Along with that, you have a good working knowledge of how to combine a host of standard validators such as CreditCard, EmailAddress, Db_RecordExists, and Hex, and standard filters such as Compress/Decompress, BaseName, Encrypt, and RealPath. But what do you do when a situation arises that’s outside the scope of the pre-packaged validators and filters?

好的,因此您可以轻松使用Zend Framework,尤其是使用Forms。 除此之外,您还具有如何结合使用许多标准验证器(例如CreditCardEmailAddressDb_RecordExistsHex )以及标准过滤器(例如Compress / DecompressBaseNameEncryptRealPath)的丰富知识 。 但是,当出现超出预打包的验证器和过滤器范围的情况时,您该怎么办?

Let’s say you want to guard against users uploading files that contain viruses, for example. You would have to write a custom validator that checks the uploads aren’t infected. Today I’ll show you how to do just that – how to write a new file validation filter for Zend Framework that uses ClamAV to ensure uploaded files are virus-free.

举例来说,您要防止用户上传包含病毒的文件。 您将必须编写一个自定义验证程序,以检查上传文件是否被感染。 今天,我将向您展示如何做到这一点–如何为Zend Framework编写一个新的文件验证过滤器,该过滤器使用ClamAV来确保上传的文件没有病毒。

向PHP添加ClamAV支持 (Adding ClamAV Support to PHP)

First you’ll need to install ClamAV support. I’m basing this installation procedure around Linux, specifically Ubuntu. If you’re using another distribution, you may need to adjust the commands accordingly. Unfortunately, if you’re using Windows however, you’ll need to use a Linux-based Virtual Appliance or setup a virtual machine running Linux to follow along since the php-clamav extension doesn’t support Windows as yet.

首先,您需要安装ClamAV支持。 我将基于Linux,特别是Ubuntu进行此安装过程。 如果您使用的是其他发行版,则可能需要相应地调整命令。 不幸的是,但是,如果您使用的是Windows,则由于php-clamav扩展尚不支持Windows,因此您需要使用基于Linux的虚拟设备或安装运行Linux的虚拟机。

Before you attempt to install ClamAv, ensure that you have the library’s dependencies installed. You’ll also want to make sure you have the PHP dev package installed so phpize is available. You can do this by running the following command:

在尝试安装ClamAv之前,请确保已安装库的依赖项。 您还需要确保已安装PHP开发包,以便phpize可用。 您可以通过运行以下命令来执行此操作:

msetter@tango:~$ sudo apt-get install php5-dev libclamav-dev clamav libclamav6 clamav-freshclam

Once you have the dependencies installed, grab a copy of the php-clamav library from sourceforge.net/projects/php-clamav and extract it to a temporary directory on your system. Navigate into the extracted library’s directory and run the following commands:

一旦安装了依赖项,就可以从sourceforge.net/projects/php-clamav中获取php-clamav库的副本,并将其解压缩到系统上的临时目录中。 导航到提取的库的目录,然后运行以下命令:

msetter@tango:~/php-clamav$ phpize
msetter@tango:~/php-clamav$ ./configure --with-clamav
msetter@tango:~/php-clamav$ make

If they all execute without errors, you’ll find a newly compiled module in the modules subdirectory. Copy the module to the directory in which the rest of your PHP modules reside. Your system may vary, but I was able to do it with:

如果它们全部执行没有错误,您将在modules子目录中找到一个新编译的模块。 将模块复制到其余PHP模块所在的目录中。 您的系统可能会有所不同,但是我能够做到:

msetter@tango:~/php-clamav$ sudo cp modules/clamav.so /usr/lib/php5/20090626+lfs/

You then need to enable the module in PHP’s configuration file. This is done pretty simply by adding the following line to php.ini and restarting Apache:

然后,您需要在PHP的配置文件中启用该模块。 这很简单,只需php.ini下行添加到php.ini并重新启动Apache:

extension=clamav.so

Finally, either run php -i from the command line or execute a simple PHP script that contains just a call to phpinfo() to verify the new extension is enabled. You should see output similar to that below.

最后,从命令行运行php -i或执行一个简单PHP脚本,其中仅包含对phpinfo()的调用,以验证是否启用了新扩展名。 您应该看到与下面类似的输出。

clamav extension in phpinfo output

The ClamAv library comes with a series of constants and functions, but in this article I will focus on just two functions, cl_scanfile() and cl_pretcode(), as all you need to do is scan the uploaded file and report what the virus is if one is found. For more information on the other available functions visit php-clamav.sourceforge.net.

ClamAv库带有一系列常量和函数,但是在本文中,我将只关注两个函数cl_scanfile()cl_pretcode() ,因为您需要做的就是扫描上传的文件并报告病毒是什么。找到一个。 有关其他可用功能的更多信息,请访问php-clamav.sourceforge.net

构建文件上传验证器 (Building the File Upload Validator)

Now that the extension is installed and enabled, let’s get underway and build the Zend Framework ClamAV file upload validator. I’ll assume that you already have a working Zend Framework project which has module support enabled and ready to go. Add support for the new validation library by adding the following line to your application.ini file:

现在已经安装并启用了扩展程序,让我们开始构建Zend Framework ClamAV文件上传验证器。 我假设您已经有一个有效的Zend Framework项目,该项目已启用模块支持并可以使用。 通过将以下行添加到application.ini文件来添加对新验证库的支持:

autoloaderNamespaces[] = "Common_"

Then, under the library directory of your Zend Framework project root, create the directory Common/Validate/File and within it a file named ClamAv.php with the following content:

然后,在Zend Framework项目根目录的库目录下,创建目录Common/Validate/File并在其中创建一个名为ClamAv.php的文件,其内容如下:

<?php
class Common_Validate_File_ClamAv extends Zend_Validate_Abstract
{
}

With that, your new validator class will be available to the project.

这样,您的新验证器类将可用于该项目。

If you’re not familiar with validators in Zend Framework, they’re a pretty straight-forward affair. You can either extend them from Zend_Validate_Abstract or Zend_Validate_Interface. For the purposes of this example, I’m basing the validator on the former. Given that, you will only have to implement two methods: the constructor and isValid().

如果您不熟悉Zend Framework中的验证器,那么它们是一件很简单的事情。 您可以从Zend_Validate_AbstractZend_Validate_Interface扩展它们。 出于本示例的目的,我将验证器基于前者。 鉴于此,您仅需实现两个方法:构造函数和isValid()

The constructor should check whether the ClamAv extension is loaded as it’s not shipped with a standard distribution of PHP.

构造函数应检查是否已加载ClamAv扩展,因为它未随标准PHP发行版一起提供。

The isValid() method will perform the core work of the validator. Normally the method validates some input and either returns true if the validation was successful or sets an error message in the errors list that is shown afterwards and returns false if the validation failed. Depending on the configuration of your form validators, returning false will either halt the form validation at that point or let the remaining validators continue to run.

isValid()方法将执行验证程序的核心工作。 通常,该方法会验证一些输入,如果验证成功,则返回true,或者在错误列表中设置一个错误消息(随后显示),如果验证失败,则返回false。 根据表单验证器的配置,返回false会在此时停止表单验证,或者让其余的验证器继续运行。

Fill out the Common_Validate_File_ClamAv class so it looks like this:

填写Common_Validate_File_ClamAv类,使其如下所示:

<?php
class Common_Validate_File_ClamAv extends Zend_Validate_Abstract
{
    const STATUS_CLEAN = 0;
    const NOT_READABLE = "fileNotReadable";
    const FILE_INFECTED = "fileInfected";

    protected $_messageTemplates = array(
        self::FILE_INFECTED => "File '%value%' is infected",
        self::NOT_READABLE => "File '%value%' is not readable");

    public function __construct() {
        if (!extension_loaded('clamav')) {
            throw new Zend_Validate_Exception(
                "ClamAv extension is not loaded");
        }
    }
 
    public function isValid($value, $file = null) {
        if ($file === null) {
            $file = array("type" => null, "name" => $value);
        }
        
        if (!Zend_Loader::isReadable($value)) {
            return $this->_throw($file, self::NOT_READABLE);
        }

        $retcode = cl_scanfile($value, $virusname);
        if ($retcode !== self::STATUS_CLEAN) {
            printf("File path: %s | Return code: %s | Virus found name: %s",
                $value, cl_pretcode($retcode), $virusname);
            return $this->_throw($file, self::FILE_INFECTED);
        }
        
        return true;
    }
    
    protected function _throw($file, $errorType) {
        $this->_value = $file["name"];
        $this->_error($errorType);
        return false;
    }
}

First a set of class constants are specified that define the return status for the virus check string templates for custom errors messages. Following that, the constructor checks for ClamAv support being available. If it’s not available, then an exception is thrown.

首先,指定一组类常量,以定义自定义错误消息的病毒检查字符串模板的返回状态。 之后,构造函数将检查是否有ClamAv支持。 如果不可用,则会引发异常。

The isValid() method checks if it the incoming $value argument contains a filename and that the file is readable. If it is, then the cl_scanfile() function is called. The return code from cl_scanfile() indicates whether the file is virus-free. If not, then the name of the virus is retrieved using the cl_pretcode() function and the information is printed.

isValid()方法检查传入的$value参数是否包含文件名,并且该文件可读。 如果是,则cl_scanfile()函数。 cl_scanfile()的返回代码指示该文件是否无病毒。 如果不是,则使用cl_pretcode()函数检索病毒名称并打印信息。

The _throw() method takes care of setting the appropriate error constant in the class and returning false to indicate that validation has failed. If this happens, the error message linked to the constant will be displayed in the upload form through the use of an error decorator on the input element.

_throw()方法负责在类中设置适当的错误常量,并返回false表示验证失败。 如果发生这种情况,链接到该常量的错误消息将通过在输入元素上使用错误装饰器以上载形式显示。

测试验证器 (Testing the Validator)

With the validator written, you’ll need a form to make use of it and test that it works. Either manually or with zf.sh, create a new action in the IndexController class of the default module and call it “fileUpload”. Add the following code to it:

编写验证器后,您将需要一个表格来使用它并测试其是否有效。 手动或使用zf.sh在默认模块的IndexController类中创建一个新动作,并将其称为“ fileUpload”。 向其添加以下代码:

<?php
class IndexController extends Zend_Controller_Action
{
...
    public function fileUploadAction() {
        $form = new Zend_Form();
        $form->setAction("/default/index/file-upload")
             ->setMethod("post");
    
        $uploadFile = new Zend_Form_Element_File("uploadfile");
        $uploadFile->addValidator(new Common_Validate_File_ClamAv())
           ->setRequired(true)
           ->setLabel("Upload file:");
       
        $form->addElement($uploadFile);
        $form->addElement(new Zend_Form_Element_Submit("submit"));
    
        if ($form->isValid($_POST)) {
            $values = $form->getValues();
            $this->view->messages = array("File uploaded");
        }
    
        $this->view->form = $form;
    }
}

Here you’ve created a simple form and set its action and method properties, a submit button, and a file element. The newly created ClamAv file validator is added to the file element. In addition, the required flag Is set to true ensuring that a file must be uploaded. Following this, both elements are added to the form and a simple if statement checks whether the form has been submitted.

在这里,您已经创建了一个简单的表单,并设置了它的操作和方法属性,一个提交按钮以及一个文件元素。 新创建的ClamAv文件验证器将添加到file元素。 此外,required标志设置为true,以确保必须上传文件。 然后,将两个元素都添加到表单中,并使用简单的if语句检查表单是否已提交。

If the form doesn’t validate after being submitted (i.e. the file has a virus), then a validation message will be displayed using the standard error message decorator. Otherwise, a message is added to the view’s messages which will be displayed to the user to indicate the upload was successful.

如果表单在提交后未通过验证(即文件中包含病毒),则将使用标准错误消息修饰符显示验证消息。 否则,将在视图的消息中添加一条消息,该消息将显示给用户以指示上传成功。

The last piece is the view script, which is shown below:

最后一部分是视图脚本,如下所示:

<h1>Zend Framework - ClamAV File Upload Validator</h1>
<?php
if (count($this->messages)) {
    echo '<ul id="messages">';
    foreach ($this->messages as $message) {
        echo "<li>" . $this->escape($message) . "</li>";
    }
    echo "</ul>";
}
echo $this->form;

As the lions share of the work already taken care of by the controller and the validator, the view script doesn’t need to do a lot. It simply displays any messages that have been set by the controller and renders the form.

由于大部分的工作已经由控制器和验证器完成,因此视图脚本不需要做很多事情。 它仅显示控制器已设置的所有消息并呈现表单。

摘要 (Summary)

After working through all that code, you now have a new validator for the Zend Framework that, via the PHP ClamAv library, will check if a file is virus free. I hope that you found this article helpful, both for showing how to create your own custom validators in the Zend Framework and for being able to ensure that you have virus free uploads in the applications that you create from here on in. If you’d like to inspect the code further, code for this article is available for cloning on GitHub.

处理完所有代码之后,您现在有了Zend Framework的新验证器,该验证器将通过PHP ClamAv库检查文件是否不含病毒。 我希望您认为本文对您有所帮助,既可以说明如何在Zend Framework中创建自己的自定义验证器,又可以确保从此处开始创建的应用程序中没有病毒上传。为了进一步检查代码,可以在GitHub上克隆本文的代码

Image via mathagraphics / Shutterstock

图片来自Mathagraphics / Shutterstock

翻译自: https://www.sitepoint.com/zf-clamav/

clamav

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值