问题
I have created a site using CakePHP 3. I have static page which has contact us form something like this:
inside contactus.ctp:
<?=$this->Form->create(); ?>
<?=$this->Form->hidden('form_type',['value' => 'contact']) ?>
<?=$this->Form->input('name',[
'label' => false,
'placeholder' => 'Your Full Name',
'required' => true
]); ?>
<?=$this->Form->input('email',[
'label' => false,
'placeholder' => 'Your Email',
'type' => 'email',
'require' => true
]); ?>
<?=$this->Form->textarea('message',[
'placeholder' => 'Your message...'
]) ?>
<?= $this->Recaptcha->display()?>
<button>Submit Query!</button>
<?=$this->Form->end(); ?>
Using the following link I created Recaptcha:
https://github.com/agiletechvn/Recaptcha
Just beside the Submit button I have Recaptcha.
In the pageController I have the submit check happening:
if($this->request->is(['post']) && $this->request->data('form_type') == 'contact'){
$name = $this->request->data('name');
$email = $this->request->data('email');
$message = $this->request->data('message');
if(!$name){
$this->Flash->set('Please enter a name' . $name,['element' => 'error']);
} elseif (!$email || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$this->Flash->set('The email you entered is invalid',['element' => 'error']);
} elseif(!$message){
$this->Flash->set('Message cannot be blank',['element' => 'error']);
} else {
if($this->Recaptcha->verify()) {
$emailObj = new Email();
$emailObj
->from(['contactus@mydomain.com' => 'Developer'])
->replyTo([$email => $name])
->to(['contactus@contactus.com'])
->template('pages/contactus')
->viewVars([
'quickAction' => [
'description' => 'Contact form',
'action' => "from: $name"
],
'name' => 'contactus@mydomain.com',
'senderName' => $name,
'email' => $email,
'message' => $message
])
->subject('Contact email from ' . $name)
->send();
$this->Flash->set('Your message has been sent', ['element' => 'success']);
}
$this->Flash->error(__('Please pass Google Recaptcha first'));
}
If I click submit button I get:
Unexpected field 'g-recaptcha-response' in POST data
I moved the reCaptcha code outside the form. Everything works correctly but the captcha but is sitting outside some random location like this:
How do I solve this issue?
回答1:
This message can show if you are using CakePHP Security Component, and this component does not recognize one of your form fields. You should unlock this field using:
$this->Form->unlockField('g-recaptcha-response');
More info: CakePHP 3.x Security Component
来源:https://stackoverflow.com/questions/45854069/unexpected-field-g-recaptcha-response-in-post-data-on-cakephp-3