我有一個使用CodeIgniter驗證庫和AJAX驗證並提交表單的聯繫表單。我的下一步是將Google的驗證碼整合到我的表單的CI中。現在官方教程有標準的PHP安裝教程和我寧願嘗試一個CI的方式,我發現了一個更新的帖子在這裏:Google Captcha Codeigniter控制器
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';
}
}