Recaptcha won't post in CodeIgniter project - codeigniter

I’ve a problem with implementing recaptcha in a CodeIgniter application.
The problem is that the recapctha_challenge_field and recaptcha_response_field do not get posted, however, the recapctcha (and those fields) is visible on the page (within the form).
The the recapctha_challenge_field and recaptcha_response_field are appearing in the HTML of the page, but not in the header when I post the form.
I’ve downloaded de recaptcha library and added it as an helper in CI.
Within the form in my view I echo the recaptcha_get_html($publickey) (with the public key set).
In my controller, I load the recaptchalib_helper and add set a form validation rule for the recapctha_challenge_field.
This is my view:
<h1>Register</h1>
<fieldset>
<legend>Personal information</legend>
<?php
echo form_open('login/create_user');
echo form_label('First name:', 'first_name');
echo form_input(
array(
'name' => 'first_name',
'id' => 'first_name',
'value' => set_value('first_name')
)
);
echo form_label('Last name:', 'last_name');
echo form_input(
array(
'name' => 'last_name',
'id' => 'last_name',
'value' => set_value('last_name')
)
);
echo form_label('Birth date:', 'birth_date');
echo form_input(
array(
'name' => 'birth_date',
'id' => 'birth_date',
'value' => set_value('birth_date')
)
);
echo form_label('E-mail:', 'email');
echo form_input(
array(
'name' => 'email',
'id' => 'email',
'value' => set_value('email')
)
);
?>
</fieldset>
<fieldset>
<legend>Login information</legend>
<?php
echo form_label('Username:', 'username');
echo form_input(
array(
'name' => 'username',
'id' => 'username',
'value' => set_value('username')
)
);
echo form_label('Password:', 'password1');
echo form_password(
array(
'name' => 'password1',
'id' => 'password1',
'value' => set_value('password1')
)
);
echo form_label('Confirm password:', 'password2');
echo form_password(
array(
'name' => 'password2',
'id' => 'password2',
'value' => set_value('password2')
)
);
$publickey = "mypublickey"; // here I entered my public key
echo recaptcha_get_html($publickey);
echo form_label(nbs(1), 'submit');
echo form_submit(
array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Registreren'
)
);
echo form_close();
?>
<?php echo validation_errors('<p class="error">'); ?>
</fieldset>
</div>
and this is a part of my controller:
function create_user() {
print_r($_POST);//for debugging
$this->load->library('form_validation');
$this->load->model('user');
$this->form_validation->set_rules('recaptcha_challenge_field', 'Captcha', 'callback_validate_captcha');
$this->form_validation->set_rules('first_name', 'First name', 'trim|xss_clean|required');
$this->form_validation->set_rules('last_name', 'Last name', 'trim|xss_clean|required');
$this->form_validation->set_rules('email', 'E-mail', 'trim|xss_clean|valid_email|callback_is_email_available|required');
$this->form_validation->set_rules('username', 'Username', 'trim|xss_clean|min_length[5]|callback_is_username_available|required');
$this->form_validation->set_rules('password1', 'Password', 'trim|xss_clean|min_length[8]|max_length[32]|required');
$this->form_validation->set_rules('password2', 'Confirm password', 'trim|xss_clean|matches[password1]|required');
if ($this->form_validation->run() == FALSE) {
$this->signup();
} else {
if ($this->user->create_user($this->input->post('username'),$this->input->post('password1'),$this->input->post('email'),$this->input->post('first_name'),$this->input->post('last_name'),$this->input->post('birth_date'))) {
$data['main_content'] = 'login/signup_successful';
$this->load->view('includes/template', $data);
} else {
$this->load->view('login/signup_form');
}
}
}
public function validate_captcha($recaptcha_challenge_field) {
$this->load->helper('recaptchalib');
$privatekey = "myprivatekey";//this is et to my private key
$resp = recaptcha_check_answer ($privatekey,
$this->input->ip_address(),
$this->input->post("recaptcha_challenge_field"),
$this->input->post("recaptcha_response_field"));
if (!$resp->is_valid) {
$this->form_validation->set_message('validate_captcha', 'Invalid Capctha code entered.');
return FALSE;
} else {
return TRUE;
}
}
The capctha fields are not set in the HTTP headers:
Form data:
csrf_test_name:8cc3f2391784867df2d46f193a65a317
first_name:Myfirstname
last_name:Mylastname
birth_date:10-12-2012
email:myemail#adres.com
username:username
password1:password
password2:password
submit:Register
What am I doing wrong?
Your sincerely,
Alwin

Does the form tag not begin within a table, tbody or tr?

Related

Unable to set validation rules loaded from config file codeigniter

My config file
config/login_rules
i have defined my login form validation rules here
<?php
/**
* SETTING VALIDATION RULES FOR THE LOGIN FORM
*/
$config['login_settings'] = array(
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|trim|min_length[6]|max_length[20]|xss_clean',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|trim|valid_email|xss_clean'
)
);
/**
* SETTING ATTRIBUTES FOR THE LOGIN FORM
*/
$config['login_attribute'] = array(
'form' => array(
'id' => 'loginform',
'class' => 'form-horizontal',
'role' => 'form'
),
'email'=> array(
'id'=>'login-username',
'class' => 'form-control',
'name'=>'email',
'placeholder' => 'Enter Email',
'value'=>set_value('email')
),
'password' =>array(
'id'=>'login-password',
'class' => 'form-control',
'name'=>'password',
'placeholder'=>'Enter Password'
),
'checkbox' =>array(
'id' => 'login-remember',
'class' => 'form-control',
'name' => 'remember_me',
'value' => '1',
'checked' => TRUE
),
'submit' =>array(
'id' => 'btn-login',
'class' => 'btn btn-success',
'name' => 'submit',
'value' => 'Login'
)
);
?>
My Controller (Login.php)
in my controller i am loading the config file trying to apply validation rules for it
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class login extends CI_Controller {
public function __construct()
{
parent::__construct();
//$this->output->enable_profiler(TRUE);
}
public function index()
{
echo 'login controller index fun';
}
public function login()
{
$this->config->load('login_rules');
$this->form_validation->set_rules($this->config->item('login_settings'));
$data["login_attrib"] = $this->config->item("login_attribute");
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login_form',$data["login_attrib"]);
}
else
{
echo 'Success';
}
}
}
?>
i am not getting any error , nor the validation rules are working
View file (login_form.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<?php echo validation_errors();
echo form_open('login/login',$form);
echo form_input($email);
echo form_input($password);
echo form_submit($submit);
echo form_close();
?>
</body>
</html>
Try this .
$this->config->load('login_rules');
$this->form_validation->set_rules($this->config->item('login_settings'));
It will be useful for you.

cakePHP validation errors not showing

So basically I have a view action in my users controller where the user can modify his information(username,first name, last name, email..) this form sends to another update action which does the saving stuff, problem is that when I submit the form and one or more fields don't meet the validation rules it doesn't show underneath each fields but the data doesn't save and
$this->User->validationErrors
outputs the errors.
my update action (accessed after submiting the form on view.ctp)
view.ctp:
<?php
echo $this->Form->create('User', array(
'inputDefaults' => array(
'div' => 'form-group',
'wrapInput' => false,
'class' => 'form-control'
),
'class' => 'well',
'url'=>array('controller'=>'users','action'=>'update'),
'id'=>'info-form'
));
?>
<fieldset>
<legend>Personal Information</legend>
<?php
echo $this->Form->input('id', array('value' => $userinfo['User']['id']));
echo $this->Form->input('User.username', array(
'label' => 'Username',
'value'=>$userinfo['User']['username']
));
?>
<td><?php echo $this->Form->error('username'); ?></td>
<?php
echo $this->Form->input('User.email', array(
'label' => 'E-mail',
'value'=>$userinfo['User']['email']
));
?>
<?php
echo $this->Form->input('User.fname', array(
'label' => 'First name',
'value'=>$userinfo['User']['fname']
));
?>
<?php
echo $this->Form->input('User.lname', array(
'label' => 'Last name',
'value'=>$userinfo['User']['lname']
));
?>
<?php
echo $this->Form->submit('Update', array(
'div' => 'form-group',
'class' => 'btn btn-success'
));
?>
</fieldset>
<?php echo $this->Form->end(); ?>
update function:
function update() {
$this->autoRender = false;
$this->User->set($this->request->data);
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Information updated Successfuly.'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-success'), 'success');
return $this->redirect('/users/view/' . $this->request->data['User']['id']);
} else {
// $errors = $this->User->validationErrors; var_dump($errors);die;
$this->Session->setFlash(__('An error occured'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-danger'), 'danger');
return $this->redirect('/users/view/' . $this->request->data['User']['id']);
}
} else {
$this->Session->setFlash(__('Request was not of POST type.'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-danger'), 'danger');
return $this->redirect('/users/index/');
}
It's because you're redirecting after - that will make it lose the validation warnings.

Error on passing data from controller to view of Codeigniter

I am facing a wired problem for more than 2 hours. I couldn't figured it out. I am trying to pass the variable "errors" from model to view but when I try to load the page it shows error saying "undefined variable: errors". I am trying to build a "register" page for registering new users.
Here is my controller for register
function register(){
if($_POST){
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|min_length[3]|is_unique[users.username]'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[5]'
),
array(
'field' => 'password2',
'label' => 'Password Confirm',
'rules' => 'trim|required|min_length[5]|matches[password]'
),
array(
'field' => 'user_type',
'label' => 'User Type',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|is_unique[users.email]|valid_email'
)
);
$this->load->library('form_validation');
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$data_array = array(
'username' => $_POST['username'],
'password' => sha1($_POST['password']),
'email' => $_POST['email'],
'user_type' => $_POST['user_type']
);
$this->load->model('user');
$userid = $this->user->create_user($data_array);
$this->session->set_userdata('userID', $userid);
$this->session->set_userdata('user_type',$_POST['user_type']);
redirect(base_url().'index.php/posts');
}
}
$this->load->helper('form');
$this->load->view('header');
$this->load->view('register_user');
$this->load->view('footer');
}
In above when there is a error in validation I set the error in $data['errors'] array.
The view is given below
<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>
But when I open the register page on browser, it shows the error saying "Undefined variable: errors". Can anyone tell me where I have done wrong?
You are not passing any data to your views. You can use the 2nd parameter to pass data to your views so rather than doing
$this->load->view('header');
$this->load->view('register_user');
$this->load->view('footer');
You want to do
$aData['errors']
$this->load->view('header', $aData);
$this->load->view('register_user', $aData);
$this->load->view('footer', $aData);
Then when you are in your view you can do
<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>

CakePHP validation not working

Iam new in cakephp ,I need to validate a form.
This is the code:
Controller:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
public function index(){
}
function add_task()
{
if(!empty($this->data)) {
//print_r($this->data);
$this->Task->set($this->data);
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
// didn't validate logic
echo $errors = $this->Task->validationErrors;
}
}
}
}
?>
Model:
<?php
class Task extends AppModel
{
public var $name = 'Task';
var $useDbConfig = 'travanco_erp';
public var $useTable = 'tbl_tasks'; // This model uses a database table 'exmp'
public var $validate = array(
'task_title_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The title field is required'
),
'task_description_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The description field is required'
),
'task_from_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The from date field is required'
),
'task_to_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The to date field is required'
)
);
}
?>
This is the view:
<div class="employeeForm" style="width:64%; padding:10px 30%;">
<?php echo $this->Form->create('test', array('class'=>'form'));?>
<fieldset style="width:36em; padding:0px 0px;">
<div style="width:475px; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#333333; font-weight:bold; margin-left:20px; margin-top:10px;">Add Task</div>
<br/>
<?php
/*echo $this->Form->input('task_ids_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Task ID',
));*/
echo $this->Form->input('task_title_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Title',
));
echo $this->Form->input('task_description_mm', array( 'type' => 'textarea',
'cols'=>60,
'rows' => 5,
'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Description',
));
echo $this->Form->input('task_from_mm', array( 'div'=>'frm_filed_new','id'=>'task_from_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'From',
));
echo $this->Form->input('task_to_mm', array( 'div'=>'frm_filed_new','id'=>'task_to_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'To',
));
?>
<br/>
<?php echo $this->Form->button('Submit', array('type'=>'submit','escape'=>true)); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>
The validation not working.
What is the error in my code?
How can i solve this?
EDIT:
It is the mistake of misconfiguration of databse.php file.Now its corrected .And the print_r($errors) displays the errors.But that not displayed in the view page , i mean near the textboxes.
This is that error array:
Array ( [task_title_mm] => Array ( [0] => The title field is required ) [task_description_mm] => Array ( [0] => The description field is required ) [task_from_mm] => Array ( [0] => The from date field is required ) [task_to_mm] => Array ( [0] => The to date field is required ) )
How can i put it in near the text box?
CakePHP is designed to automatically validate model and display validation errors. Auto validation runs on model save. In your case:
$this->Task->save($this->request->data);
above will trigger validation. There is no need to run: $this->Task->validates() - If you do so, you also have to take care of displaying validation error by your own. So I think you simply should try:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
function add_task()
{
if ($this->request->is('post')) {
// If the form data can be validated and saved...
if ($this->Task->save($this->request->data)) {
//saved and validated
}
}
}
}
?>
one thing i noticed in your code that you are writing in your model
public var $validate=array();
instead try
public $validate= array() or var $validate=array();
Validation should work after words.
Thanks :)
Try this:
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
$this->validateErrors($this->Task);
$this->render();
}

Validation Errors not showing

I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.

Resources