Ion Auth - Create_User In Another Controller Does Not Work - codeigniter

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.
:)

Related

User not redirecting to the page after registering but registration working successfully in codeigniter

The problem here is that registration is working properly but it is not redirecting to certain page which i want.because to go to that page which is in another controller, id should be set on session .bt even after setting id to session it not working .help me out thank you..here is the code
controller
public function newregister()
{
if($this->session->userdata("passenger_id"))
return redirect("user/dashboard");
$this->load->view('userregister');
}
public function register()
{
$this->form_validation->set_rules('fname', 'Fullname', 'required|min_length[5]|max_length[42]|trim|alpha_numeric_spaces');
$this->form_validation->set_rules('uname', 'Username', 'trim|required|min_length[5]|max_length[12]|is_unique[passengers.uname]');
$this->form_validation->set_rules('dob', 'Date of birth', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('mobile', 'Mobile Number', 'trim|required|max_length[10]|min_length[10]');
$this->form_validation->set_rules('city', 'City', 'required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('pword', 'Password', 'trim|required|min_length[8]');
$this->form_validation->set_rules('confirmpword', 'Confirm Password', 'trim|required|min_length[8]|matches[pword]');
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run()){
$this->load->model('user_model');
$pdata=array(
'passenger_id'=>$this->input->post('passenger_id'),
'fname'=>$this->input->post('fname'),
'uname'=>$this->input->post('uname'),
'dob'=>$this->input->post('dob'),
'gender'=>$this->input->post('gender'),
'mobile'=>$this->input->post('mobile'),
'city'=>$this->input->post('city'),
'email'=>$this->input->post('email'),
'pword'=>sha1($this->input->post('pword')),
'confirmpword' =>sha1($this->input->post('confirmpword'))
);
if($this->user_model->user_validate($pdata))
{
$this->session->set_userdata($pdata);
$this->session->set_flashdata('message','You have successfully registered to SMS TravelBook... ');
return redirect('user/dashboard');
}
else{
$this->session->set_flashdata('message','Sorry failed to register');
return redirect('home/register');
}
}
else{
$this->newregister();
}
}
Model
public function user_validate($pdata)
{
return $this->db->insert('passengers',$pdata);
}
Your main issue seems to be that you're setting session before even saving data into the database. Also, keep in mind that you shouldn't store passwords in session, I've written the rectified code, comments are mentioned wherever necessary, you're free to tweak it according to your needs. Hope it helps you.
Controller
public function newregister()
{
if($this->session->userdata("passenger_id")){
redirect("user/dashboard");
}else{
$this->load->view('userregister');
}
}
public function register()
{
$this->form_validation->set_rules('fname', 'Fullname', 'required|min_length[5]|max_length[42]|trim|alpha_numeric_spaces');
$this->form_validation->set_rules('uname', 'Username', 'trim|required|min_length[5]|max_length[12]|is_unique[passengers.uname]');
$this->form_validation->set_rules('dob', 'Date of birth', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('mobile', 'Mobile Number', 'trim|required|max_length[10]|min_length[10]');
$this->form_validation->set_rules('city', 'City', 'required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('pword', 'Password', 'trim|required|min_length[8]');
$this->form_validation->set_rules('confirmpword', 'Confirm Password', 'trim|required|min_length[8]|matches[pword]');
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if($this->form_validation->run()){
$pdata=array(
'passenger_id' => '', // empty because no value yet(value not inserted in db)
'fname' => $this->input->post('fname'),
'uname' => $this->input->post('uname'),
'dob' => $this->input->post('dob'),
'gender' => $this->input->post('gender'),
'mobile' => $this->input->post('mobile'),
'city' => $this->input->post('city'),
'email' => $this->input->post('email'),
'pword' => sha1($this->input->post('pword')),
'confirmpword' => sha1($this->input->post('confirmpword'))
);
$this->load->model('user_model');
$dbId = $this->user_model->user_validate($pdata); // get the inserted id
if($dbId) // check if query was successful
{
$pdata=array(
'passenger_id' => $dbId,
'fname' => $this->input->post('fname'), // or $pdata['fname']
'uname' => $this->input->post('uname'), // or $pdata['uname']
'dob' => $this->input->post('dob'), // ...
'gender' => $this->input->post('gender'),
'mobile' => $this->input->post('mobile'),
'city' => $this->input->post('city'),
'email' => $this->input->post('email'),
'pword' => sha1($this->input->post('pword')), // avoid storing password in session
'confirmpword' => sha1($this->input->post('confirmpword')) // avoid storing password in session
);
/* or you could just do - $pdata['passenger_id'] = $dbId;(because rest of the data is same) */
$this->session->set_userdata($pdata);
$this->session->set_flashdata('message','You have successfully registered to SMS TravelBook... ');
redirect('user/dashboard');
}
else{
$this->session->set_flashdata('message','Sorry failed to register');
redirect('home/register');
}
}
else{
$this->newregister();
}
}
Model
public function user_validate($pdata)
{
return ($this->db->insert('passengers', $pdata)) ? $this->db->insert_id() : false; // return insert_id if successful else return false
}

How to validate fields

I want to insert validate data into database.
My code is like below, where submit is my button name and name, email, mobile is my form fields:
if($this->input->post('submit'))
{
$name = $this->input->post('name');
$email = $this->input->post('email');
$mobile = $this->form_validation->set_rules('mobile', 'Mobile','trim|required|numeric');
$query = $this->my_model->insertdata($name, $email, $mobile);
}
How can I validate form fields if I have written code like above?
You should use Form Validation Library.
First, autoload it:
Open application/config/autoload.php and edit line 61 like below:
$autoload['libraries'] = array('form_validation');
Now, you can validate your form in your controller. Here is an example for you:
public function some_function()
{
$this->form_validation->set_rules('input_name', 'input human name', 'required');
if ($this->form_validation->run() === false)
{
//return some error here
}
else
{
// send data to your model (e.g. $this->Some_model->some_function())
}
}
Please see Form Validation Library Guide to see all references and examples. Also please follow this order for submitting forms: View -> Controller -> Model.
first, you are putting insecure data into your database.
$data = [
'name' => html_escape($this->input->post('name'),
'email' => html_escape($this->input->post('email'),
'mobile' => html_escape($this->input->post('mobile');
];
$this->form_validation->set_rules('mobile',Mobile','trim|required|numeric');
$this->form_validation->set_rules('name',name','trim|required');
$this->form_validation->set_rules('email',Email','trim|required|valid_email');
if ($this->form_validation->run() === false)
{
//print error
}else
{
$this->db->insert('TABLE', $data);
}
public function register()
{
$this->form_validation->set_rules('username', 'Usename Name', 'trim|required|min_length[3]|max_length[30]');
$this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email|is_unique[jobseeker_registration.email]');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|numeric');
if ($this->form_validation->run() === false)
{ $this->load->view('register'); }
else
{
$data = array(
'name' => $this->input->post('name'),
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'password' => $this->input->post('password')
);
$this->Jobseeker_model->insertdata($data)
}
}
This code is work for me very well for form validation

CodeIgniter custom validation library function not working

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

CodeIgniter custom validate function not working

I am using CodeIgniter 2.3.1 and created a form_validation.php file in config and the content is as below.
<?php
$config = array(
array(
'field' => 'firstname',
'label' => 'First Name',
'rules' => 'required'
),
array(
'field' => 'lastname',
'label' => 'Last Name',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email|callback_unique_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|matches[confirm_password]'
),
array(
'field' => 'confirm_password',
'label' => 'Confirm Password',
'rules' => 'required'
)
);
function unique_email($email) {
if($email == 'm#gmail.com') {
$this->form_validation->set_message('unique_email', 'Hello World !');
return false;
}
}
?>
And checking the form_validation in register function of user controller. The code is below.
public function register() {
$this->load->helper('form');
$data['message'] = '';
if($this->input->post('submit')) {
$this->load->library('form_validation');
if($this->form_validation->run() == FALSE) {
$data['message'] = 'User could not be saved.';
} else {
$user_data['firstname'] = $this->input->post('firstname');
$user_data['lastname'] = $this->input->post('lastname');
$user_data['email'] = $this->input->post('email');
$user_data['password'] = md5($this->input->post('password'));
if($this->user_model->insert($user_data)) {
if($this->user_model->login($user_data)) {
$this->session->set_flashdata('message', 'User saved successfully.');
redirect('/user', 'refresh');
}
}
}
}
$this->load->view('user/register', $data);
}
But I am not getting validation message for the custom method. Please suggest me how to do it?. The work is more appreciated.
Have a look at the following documentation: http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#callbacks
As you can see int the documentation, the custom validation function actually belongs in the controller, and not in the config file. By moving the validation function to the controller, the callback function should start getting called.
Another fun fact, people can access this unique_email function through a url (ie. http://yoursite.com/index.php/user/unique_email). To avoid this, we can write the function as a private function by simply placing an underscore at the beginning of the function, like so:
function _unique_email($email) {
...
}
You can then call the function in your validation by using the new function name in your config (notice the extra underscore in the callback:
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email|callback__unique_email'
)
In the end, your controller should look similar to the following:
class User extends CI_Controller {
public function register() {
$this->load->helper('form');
$data['message'] = '';
if($this->input->post('submit')) {
$this->load->library('form_validation');
if($this->form_validation->run() == FALSE) {
$data['message'] = 'User could not be saved.';
} else {
$user_data['firstname'] = $this->input->post('firstname');
$user_data['lastname'] = $this->input->post('lastname');
$user_data['email'] = $this->input->post('email');
$user_data['password'] = md5($this->input->post('password'));
if($this->user_model->insert($user_data)) {
if($this->user_model->login($user_data)) {
$this->session->set_flashdata('message', 'User saved successfully.');
redirect('/user', 'refresh');
}
}
}
}
$this->load->view('user/register', $data);
}
function _unique_email($email) {
if($email == 'm#gmail.com') {
$this->form_validation->set_message('unique_email', 'Hello World !');
return false;
}
}
}
Your config would look similar to the following:
$config = array(
array(
'field' => 'firstname',
'label' => 'First Name',
'rules' => 'required'
),
array(
'field' => 'lastname',
'label' => 'Last Name',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email|callback__unique_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|matches[confirm_password]'
),
array(
'field' => 'confirm_password',
'label' => 'Confirm Password',
'rules' => 'required'
)
);
I used this answer and got error:
Unable to access an error message corresponding to your field name.
In function _unique_email instead set_message('unique_email', 'Hello World !'); should be set_message('_unique_email', 'Hello World !'); like this:
function _unique_email($email) {
if($email == 'm#gmail.com') {
$this->form_validation->set_message('_unique_email', 'Hello World !');
return false;
}
}

Validate form fields in controller with a hasMany relation

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?

Resources