【问题标题】:How to validate Google reCaptcha v2 using phalcon/volt forms?如何使用 phalcon/volt 表单验证 Google reCaptcha v2?
【发布时间】:2015-06-12 09:38:52
【问题描述】:

您如何使用 volt 和 phalcon 技术验证新的 Google reCaptcha?

(只是想分享我为使其工作所做的工作,请参阅下面的答案,希望对您有所帮助...)

【问题讨论】:

    标签: php recaptcha phalcon volt


    【解决方案1】:

    你需要什么

    • 验证器(本例中为 RecaptchaValidator)
    • Form 实现
    • Controller 实现(实际上这里不需要更改,但为了完整性......)
    • View 实现
    • (可选)为您的 recaptcha 密钥和 url 配置条目(这样更好/更干净)
    • (可选)用于自动渲染的 recaptcha 元素(如果您更喜欢渲染方法)

    验证器

    验证器是其中最关键的部分,所有其他的东西都相当直观......

    use \Phalcon\Validation\Validator;
    use \Phalcon\Validation\ValidatorInterface;
    use \Phalcon\Validation\Message;
    
    class RecaptchaValidator extends Validator implements ValidatorInterface
    {
        public function validate(\Phalcon\Validation $validation, $attribute) 
        {
            if (!$this->isValid($validation)) {
                $message = $this->getOption('message');
                if ($message) { // Add the custom message defined in the "Form" class
                    $validation->appendMessage(new Message($message, $attribute, 'Recaptcha'));
                }
                return false;
            }
            return true;
        }
    
        /********************************************
         *  isValid - Return Values
         *  =======================
         *  true .... Ok
         *  false ... Not Ok
         *  null .... Error
         */
        public function isValid($validation) 
        {
            try {
                $config = $validation->config->recaptcha; // not needed if you don't use a config
                $value =  $validation->getValue('g-recaptcha-response');
                $ip    =  $validation->request->getClientAddress();
    
                $url = $config->verifyUrl; // or 'https://www.google.com/recaptcha/api/siteverify'; without config
                $data = ['secret'   => $config->secretKey, // or your secret key directly without using the config
                         'response' => $value,
                         'remoteip' => $ip,
                        ];
    
                // Prepare POST request
                $options = [
                    'http' => [
                        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                        'method'  => 'POST',
                        'content' => http_build_query($data),
                    ],
                ];
    
                // Make POST request and evaluate the response
                $context  = stream_context_create($options);
                $result = file_get_contents($url, false, $context);
                return json_decode($result)->success;
            }
            catch (Exception $e) {
                return null;
            }
        }
    }
    

    表单(类)实现

    class SignupForm extends Form
    {
        public function initialize($entity = null, $options = null) 
        {
            // Name (just as an example of other form fields)
            $name = new Text('name');
            $name->setLabel('Username');
            $name->addValidators(array(
                new PresenceOf(array(
                    'message' => 'Please enter your name'
                ))
            ));
            $this->add($name);
    
            // Google Recaptcha v2
            $recaptcha = new Check('recaptcha');
            $recaptcha->addValidator(new RecaptchaValidator([
                'message' => 'Please confirm that you are human'
            ]));
            $this->add($recaptcha);
    
            // Other form fields...
    }
    

    控制器实现

    尽管控制器与其他所有形式相同,但为了完整起见,这里举个例子...

    class SessionController extends \Phalcon\Mvc\Controller
    {
        public function signupAction()
        {
            $form = new SignupForm();
            if ($this->request->isPost()) {
                if ($form->isValid($this->request->getPost()) != false) 
                {
                    // Add user to database, do other checks, etc.
                    // ...
                }
            }
    
            $this->view->form = $form;
        }
    }
    

    查看实施

    对于视图,您可以将 html 放在那里,也可以让它由引擎呈现。如果您希望它被渲染(例如{{ form.render('recaptcha') }}),您还必须创建一个Recaptcha 元素,而不是使用默认值之一(请参阅此答案中的最后一点)。

    ...
    
    {{ form('class':'signupForm') }}
    <fieldset>
    
        <div>{{ form.label('name') }}</div>
            {{ form.render('name') }}
            {{ form.messages('name') }}
    
        <!-- other elements here -->        
        <!-- ...                 -->
    
        <div class="g-recaptcha" data-sitekey="{{ this.config.recaptcha.publicKey }}"></div>
        {{ form.messages('recaptcha') }}
    

    如果您不想为您的公钥使用配置(下一节),只需将 data-sitekey 的值设置为您的个人 (Google reCaptcha) 公钥。

    也不要忘记在某处(例如,在您的 html 头部部分)包含脚本 (&lt;script src='https://www.google.com/recaptcha/api.js'&gt;&lt;/script&gt;)。

    (可选)配置

    如果您想使用配置来存储您的验证码密钥,请将以下内容添加到您的 config/config.php ...

    // config/config.php
    
    return new \Phalcon\Config([
    
        'application' => [
            'controllersDir' => __DIR__ . '/../../app/controllers/',
            'modelsDir'      => __DIR__ . '/../../app/models/',
            'formsDir'       => __DIR__ . '/../../app/forms/',
            'viewsDir'       => __DIR__ . '/../../app/views/',
            'pluginsDir'     => __DIR__ . '/../../app/plugins/',
            'libraryDir'     => __DIR__ . '/../../app/library/',
            'cacheDir'       => __DIR__ . '/../../app/cache/',
            'baseUri'        => '/',
        ],
    
        // other configs here
        // ...
    
        'recaptcha' => [
            'publicKey' => 'your public key',
            'secretKey' => 'your private key',
            'verifyUrl' => 'https://www.google.com/recaptcha/api/siteverify',
        ],
    ]);
    

    为了能够访问您视图中的配置,您可能还需要将$di-&gt;set('config', $config); 添加到您的依赖注入器中(通常在config/services.php 中)。

    (可选)Recaptcha 元素

    如果您希望为您呈现您的验证码(而不是将div 直接放在视图中),您将需要一个单独的\Phalcon\Forms\Element\ ...

    class Recaptcha extends \Phalcon\Forms\Element
    {
        public function render($attributes = null) {
            return '<div class="g-recaptcha" data-sitekey="'
                .$this->config->recaptcha->publicKey
                .'"></div>';
        }
    }
    

    您还必须相应地更改您的Form:

    // ...
    $recaptcha = new Recaptcha('recaptcha');
    $recaptcha->addValidator(new RecaptchaValidator([
        'message' => '...'
    ]));
    // ...
    

    最后还有你的View:

    {{ form.render('recaptcha') }}
    

    【讨论】:

      猜你喜欢
      • 2015-03-10
      • 2020-05-21
      • 2015-06-15
      • 1970-01-01
      • 2016-03-12
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      相关资源
      最近更新 更多