我有一个使用 CodeIgniter 验证库和 AJAX 来验证和提交表单的联系表单。我的下一步是将 Google 的验证码集成到我的表单的 CI 中。现在官方教程有一个标准 php 设置教程,我更喜欢尝试一种 CI 方式,我在这里找到了更新的帖子:
http://blog.russkern.com/integrating-recaptcha-into-codeigniter-forms/
我遵循了他的指示,但我不确定如何在放置函数和 if 语句与我的其他 AJAX/验证语句方面实现控制器。
以前有没有人遇到过这个问题,或者有没有办法在我已经拥有的东西中实施?当函数位于顶部但将其余部分集成到我的控制器中时,我的表单验证词。
这是我的代码:
看法:
/* Form code is here /*
require_once('php/recaptchalib.php');
$publickey = "my.public.key";
echo recaptcha_get_html($publickey);
带有验证码验证的控制器包括:
class Contact extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('form_validation');
}
public function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Name','trim|required|htmlspecialchars|max_length[30]|xss_clean');
$this->form_validation->set_rules('email','Email Address','trim|valid_email|required|htmlspecialchars|max_length[100]|xss_clean');
$this->form_validation->set_rules('message','Message','trim|required|htmlspecialchars|xss_clean');
$this->form_validation->set_rules('recaptcha_challenge_field','challenge','trim|required|callback_captcha_check');
$this->form_validation->set_error_delimiters('<div id="errors">• ','</div>');
if($this->input->is_ajax_request()) {
$respond = array();
if($this->form_validation->run() == FALSE) {
$respond['result'] = 'false';
$respond['errors'] = validation_errors();
} else {
$respond['result'] = 'true';
$this->session->set_flashdata('success', 1);
$respond['redirect'] = base_url().'contact';
}
return $this->output->set_output(json_encode($respond));
} else {
if($this->form_validation->run() == FALSE) {
$respond['errors'] = validation_errors();
} else {
$this->session->set_flashdata('success', 1);
redirect('contact');
}
}
$data['page_title'] = 'Contact';
$data['content'] = 'contact';
$this->load->view('template', $data);
}
}
这是我需要放入控制器中的内容...当我将其放在索引函数上方时,验证有效,因此我知道它会起作用,但不确定如何集成到控制器中:
function captcha_check($str) {
require_once('php/recaptchalib.php');
$privatekey = "private.key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
$this->form_validation->set_message('captcha_check', 'The reCAPTCHA wasn\'t entered correctly. Go back and try it again.');
return FALSE;
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn’t entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
echo 'hello';
}
}