Config/login_rules.php
Here for the callback function check_email_existence
I want to pass three parameters which are (email,table, field)
<?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|check_email_existence'
)
);
?>
I have extended the form validation helper libraries/MY_Form_validation.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
protected $CI;
public function __construct($config = array())
{
parent::__construct($config);
$this->CI =& get_instance();
}
function check_email_existence($email,$table,$field) {
$this->CI->form_validation->set_message('check_email_existence', 'This %s id is not registered.');
$query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $field = '".$email."' ");
$row = $query->row();
return ($row->count > 0) ? 'success' : 'failure';
}
}//class
?>
A callback function accepts two parameters: ($postdata, $param).
$param receives whatever you define as the rule's parameter via [...] after the rule's name:
'rules' => 'required|trim|valid_email|xss_clean|check_email_existence[table,field]'
function check_email_existence($email, $param) {
// extract table and field from $param
...
Related
I've taken the "auth" controller and copied it and renamed it as "site". I have renamed the references to views etc. to "site". When I go to www.mysite/index.php/site/create_user the form loads fine. However on hitting submit I get redirected to www.mysite.com/index.php/site/login and nothing is added to the database. Can anyone tell me why this does not work? My site controller is below:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Site extends CI_Controller {
//
//Authentication
//
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library(array('ion_auth','form_validation'));
$this->load->helper(array('url','language'));
$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
$this->lang->load('auth');
}
//Function to log the user in
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{
// check to see if the user is logging in
// check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/', 'refresh');
}
else
{
// if the login was un-successful
// redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('site/login', 'refresh'); // use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{
// the user is not logging in so display the login page
// set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->_render_page('site/login', $this->data);
}
}
//Function to log the user out
function logout()
{
$this->data['title'] = "Logout";
// log the user out
$logout = $this->ion_auth->logout();
// redirect them to the login page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('site/login', 'refresh');
}
//Function to create a user
function create_user()
{
$this->data['title'] = "Create User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
{
//redirect('site/login', 'refresh');
}
$tables = $this->config->item('tables','ion_auth');
// validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('create_user_validation_fname_label'), 'required');
$this->form_validation->set_rules('last_name', $this->lang->line('create_user_validation_lname_label'), 'required');
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email|is_unique['.$tables['users'].'.email]');
$this->form_validation->set_rules('phone', $this->lang->line('create_user_validation_phone_label'), 'required');
$this->form_validation->set_rules('company', $this->lang->line('create_user_validation_company_label'), 'required');
$this->form_validation->set_rules('password', $this->lang->line('create_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('create_user_validation_password_confirm_label'), 'required');
if ($this->form_validation->run() == true)
{
$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
$email = strtolower($this->input->post('email'));
$password = $this->input->post('password');
$additional_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'phone' => $this->input->post('phone'),
);
}
if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data))
{
// check to see if we are creating the user
// redirect them back to the admin page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("site", 'refresh');
}
else
{
// display the create user form
// set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name'),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name'),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email'),
);
$this->data['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company'),
);
$this->data['phone'] = array(
'name' => 'phone',
'id' => 'phone',
'type' => 'text',
'value' => $this->form_validation->set_value('phone'),
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password',
'value' => $this->form_validation->set_value('password'),
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password',
'value' => $this->form_validation->set_value('password_confirm'),
);
$this->_render_page('site/create_user', $this->data);
}
}
//Function to render the page
function _render_page($view, $data=null, $returnhtml=false)//I think this makes more sense
{
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $returnhtml);
if ($returnhtml) return $view_html;//This will return html on 3rd argument being true
}
}
This exact code works when in the auth controller. When in the site controller I make it so you must login and you must be an admin to make a user (i.e. uncommenting out this line //redirect('site/login', 'refresh');) then it also works, but for some reason when that line is commented it works in the auth controller but not the site controller.
Any help is much appreciated. I've tried to figure it out but can't see why it works in one and not the other (and why it works in site but only as an admin when that code is uncommented and not at all when it is commented, whilst in auth it works in either case).
Thanks in advance.
The reason you get redirected is one of two reasons.
First : $this->_render_page('site/login', $this->data);
When you hit the submit button it is still pointing to the login controller.
Second : if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
The create user function in the Auth controller is for admins only, You will have to // out the code or you will be redirected to the login page due to not being logged and not being an admin.
try this:
//$this->_render_page('site/login', $this->data);
//if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
By marking out these two lines you should be able to veiw and submit your page without being redirected.
:)
I have started to create a controller called User in codeigniter
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array( 'encrypt', 'form_validation' ));
}
public function index()
{
}
/*
* Create loginform
* Parameters: void
* Return: html of loginform;
*/
public static function loginform() {
// Login form setup
$loginform_data = array();
$loginform_data['attributes'] = array('id' => 'loginform');
$loginform_data['username'] = array(
'name' => 'username',
'id' => 'username',
'value' => '',
'maxlength' => '100'
);
$loginform_data['pass'] = array(
'name' => 'pass',
'id' => 'pass',
'value' => '',
'maxlength' => '100'
);
$contentdata = array();
$contentdata['loginform'] = $this->load->view('partials/forms/login', $loginform_data, true);
return $contentdata;
}
/*
* Check login username, password from form
* Parameters: void
* Return: void;
*/
public function login() {
$name = $this->input->post('username');
$pass = $this->input->post('pass');
$this->form_validation->set_rules('username', 'Användarnamn', 'required');
$this->form_validation->set_rules('pass', 'Lösenord', 'required');
if ($this->form_validation->run() == false)
{
$this->load->view('home');
}
else
{
$this->load->view('formsuccess');
}
}
}
I can call the user/login - function through the url. But I can't call User::loginform() from another controller. Shouldn't I be able to do that?
Here's what I'm trying: (from my Home-class)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
//Create login and register-forms
$this->load->helper('form');
//Registration form setup
$registerform_data = array();
$registerform_data['attributes'] = array('id' => 'registerform');
$registerform_data['company'] = array(
'name' => 'name-company',
'id' => 'name-company',
'value' => '',
'maxlength' => '100'
);
$registerform_data['orgnr'] = array(
'name' => 'orgnr-company',
'id' => 'orgnr-company',
'value' => '',
'maxlength' => '100'
);
$registerform_data['contact'] = array(
'name' => 'contact-company',
'id' => 'contact-company',
'value' => '',
'maxlength' => '100'
);
$registerform_data['phonecompany'] = array(
'name' => 'phone-company',
'id' => 'phone-company',
'value' => '',
'maxlength' => '100'
);
$registerform_data['emailcompany'] = array(
'name' => 'email-company',
'id' => 'email-company',
'value' => '',
'maxlength' => '100'
);
//What content to pass to view
$contentdata = array();
$contentdata['loginform'] = User::loginform();
$contentdata['registerform'] = $this->load->view('partials/forms/registration', $registerform_data, true);
$this->load->view('home', $contentdata);
}
}
$contentdata['loginform'] = User::loginform(); gives me error:Fatal error: Class 'User' not found in C:\Program...
What am I missing?
While you are extending Home class ,extend to User controller like
require_once(APPPATH.'controllers/user.php');
class Home extends User {
Because you need to extract the function from User class and then it will Inherit the parent class User functions And since login_form is your public function in User controller,you can call this in Home controller now.And no need to use Static here I think so.
There is also an way to do this.Just write the login_form function in an helper and call it on both the controllers then your problem may solve.
Edit: As #IJas said,we need to include the controller file that you are extending.
I've created custom validation library class MY_Form_validation as MY_Form_validation.php in application/libraries as follows.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct($rules = array()) {
parent::__construct($rules);
}
public function file_required($file) {
if($file['size']===0) {
$this->set_message('file_required', 'Uploading a file for %s is required.');
return false;
}
return true;
}
}
?>
In my validation function I've included following rules as follows.
public function validate() {
$this->load->library('form_validation');
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|good|file_required|xss_clean'
),
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run()) {
return true;
}
return false;
}
The core validation rules are working fine but custom rule is not working. So please help me to get the soultion and Its literally wasting my time. The work would be more appreciated.
As far as i understand your function always return true. Because of $file Not $_FILES
public function file_required($file) {
if($_FILES[$file]['size']===0) {
$this->set_message('file_required', 'Uploading a file for %s is required.');
return false;
}
return true;
}
Check the rules in the function validate()
What I think it's incorrect:
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|good|file_required|xss_clean'
),
);
What I think is correct:
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|file_required|xss_clean'
),
);
I think good is not a php function, or an internal codeigniter function.
Edit:
What about using:
if ($file['size'] == 0) {
Instead of
if ($file['size'] === 0) {
Using === means the value MUST BE integer 0, but if $file['size'] returns 0 as string the if won't be true, and the function always will return true.
I had the same problem and found the cause while looking in CodeIgniter's source code. It seems the writers thought that if a field didn't have "required", then it would just skip all the rules and always return that the form has validated. See it for yourself from their code:
// If the field is blank, but NOT required, no further tests are necessary
if ( ! in_array('required', $rules) AND is_null($postdata))
However, if you add "callback_" in front of your rule, you can still make it run, for the procedure, look here:
https://www.codeigniter.com/userguide2/libraries/form_validation.html#callbacks
I'm having some issues with validating form fields inside my controller, for testing purposes.
I have my model Experience with hasMany ExperienceDetail. ExperienceDetail belongsTo Experience.
I created a form using the FormHelper which contains the following:
index.ctp
<?php
echo $this->Form->create('Experience', array('action' => 'index'));
echo $this->Form->input('Experience.date', array(
'label' => array(
'text' => 'Datum'),
'type' => 'date',
'dateFormat' => 'DMY',
'monthNames' => false,
'minYear' => date('Y') - 10,
'maxYear' => date('Y')
)
);
echo $this->Form->input('Experience.test');
echo $this->Form->input('ExperienceDetail.vertrekstation');
echo $this->Form->end('Verstuur!');
?>
There are some more fields provided with ExperienceDetail, but these are irrelevant for this matter.
Experience.php
<?php
class Experience extends AppModel {
public $name = 'Experience';
public $hasMany = 'ExperienceDetail';
public $validate = array(
'vertrekstation' => array(
'rule' => 'notEmpty',
'message' => 'Voer een vertrekstation in',
'required' => true
),
'test' => array(
'rule' => 'notEmpty',
'message' => 'Test mag niet leeg zijn!'
)
);
}
?>
ExperienceDetail.php
<?php
class ExperienceDetail extends AppModel {
public $name = 'ExperienceDetail';
public $belongsTo = 'Experience';
public $validate = array(
'vertrekstation' => array(
'rule' => 'notEmpty',
'message' => 'Voer een vertrekstation in'
)
);
}
?>
ExperiencesController.php
<?php
class ExperiencesController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public function index() {
// $this->layout = 'default_orig';
$this->set('title_for_layout', 'De OV-Ervaringenmeter!');
// LOAD Model Carrier
$this->loadModel('Carrier');
$this->set('carrier', $this->Carrier->find('list', array('order' => array('Carrier.name' => 'asc'))));
// Check if form is allready filled
if($this->request->is('post')) {
$this->Experience->set($this->request->data);
$this->Session->setFlash('No if or else statement is called');
if ($this->Experience->validates()) {
$this->Session->setFlash('Validates!');
}
}
}
}
?>
The problem is: when I send the form and leave test empty, it provides me the validation error which I've set up in the Model. But when I leave vertrekstation empty, it doesn't provide me any errors that belongs to the input field.
What am I doing wrong and how am I able to get these errors printed?
<? if ( ! defined('BASEPATH')) exit();
class Registration extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('registration_model');
}
public function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email|callback_email_available');
if($this->form_validation->run() == FALSE) {
$this->load->view('registration');
} else {
$this->registration_model->add_user();
}
}
# Check E-mail
public function email_available($email) {
$this->db->select('email');
$this->db->where('email', $email);
$query = $this->db->get('users');
$result = $query->row();
if(!empty($result)) {
$this->form_validation->set_message('email_available', 'This e-mail belongs to another user.');
return FALSE;
} else {
return TRUE;
}
}
}
?>
I have a registration form with Form Validation.
And I have a callback function to validate email uniqueness.
All code works fine, but I can directly access to callback function with errors
examle.com/registration/email_available
A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for Registration::email_available()
Filename: controllers/registration.php
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: email
Filename: controllers/registration.php
How can I deny direct access to callback function?
You can prefix the method name with an _ to deny access through HTTP request.
My suggestion is to tuck your validation rules into a separate file. CodeIgniter supports this by allowing you to save validation configurations in config/form_validation.php. Take a look at the Form Validation Documentation, specifically the section labelled Saving Sets of Validation Rules to a Config File.
Your controller's index:
public function index() {
$this->load->library('form_validation');
if($this->form_validation->run('submit_registration') == FALSE) {
$this->load->view('registration');
}
else{
$this->registration_model->add_user();
}
}
config/form_validation.php
$config = array
(
'submit_registration' => array
(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|email_available'
),
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|alpha_numeric|etc'
)
),
'some_other_submission' => array(
array(
'field' => 'somefield',
'label' => 'SomeField',
'rules' => 'some|rules'
),
array(
'field' => 'getit',
'label' => 'Get The Point?',
'rules' => 'trim'
)
)
);
libraries/MY_Form_validation.php
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array()){
parent::__construct($config);
}
function email_available($email){
$CI =& get_instance();
//check your database with the $CI variable...
if(email_exists) return TRUE;
else return FALSE;
}
}