How to access data from form validating controller in codeigniter? - php

I followed the tutorial for making a registration form with validation, with 2 views and 1 controller.
I wrote this in the controller:
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]|max_length[16]|xss_clean|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('register_form');
}
else
{
$this->load->view('register_success');
$data = array(
'IDUser' => NULL ,
'Username' => "$username" ,
'Password' => 'password' ,
'Email' => 'email' ,
'Gender' => 'gender' ,
'Birthday' => 'bday' ,
);
$this->db->insert('Accounts', $data);
}
}
First it is executes a working sql insert. After, a validation. Nevertheless, the values loaded from the database are not those from the validation. Instead, they are the same plain text in the array.
I don't want to get the values directly from the form/view with POST; that's pointless. What do i do? I'm new to Codeigniter and not that familiar with OOP PHP.

You just have to use Codeigniter Input class : http://ellislab.com/codeigniter/user-guide/libraries/input.html
So in your case:
$username = $this->input->post('username');
$password = $this->input->post('password');
$passconf = $this->input->post('passconf');
$email = $this->input->post('email');

dragu is correct but please use this format:
$username = $this->input->post('username', TRUE);
the TRUE tells codeigniter to XSS clean which is a security feature you definitely want. Thats also why you put XSS clean in the form validation. from yr example:
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]|max_length[16]|xss_clean|callback_username_check');
If the form fails validation, then CI can display the results in the form again. having xss_clean in the validation cleans those values.

Related

Add user on Codeigniter 3

Hi i am new here and i dont know how to use codeigniter and now im confused. So i am currently trying to add user data to the database using codeigniter 3.1.10 . When i click the " save " button there's nothing to display. The page was refresh
Can you help me please?
Models:
function add_user($data) {
$this->db->set("username",$data["username"]);
$this->db->set("password",$data["password"]);
$this->db->set("indirizzo",$data["indirizzo"]);
$this->db->set("citta",$data["citta"]);
$this->db->set("cap",$data["cap"]);
$this->db->insert("user");
$ins_id =$this->db->insert_id();
return $ins_id;
}
Controllers:
function add() {
$this->load->library('form_validation');
$this->form_validation->set_rules('save', '', 'trim|required|number');
if ($this->form_validation->run()) :
$data = array(
"username"=>$this->input->post("username"),
"password"=>$this->input->post("password"),
"indirizzo"=>$this->input->post("indirizzo"),
"citta"=>$this->input->post("citta"),
"cap"=>$this->input->post("cap"),
);
$user_id= $this->user_model->add_user($data);
$this->log_model->scrivi_log($user_id,"user","add");
$this->session->set_flashdata('feedback', 'User added.');
redirect("user/pageuser/".$user_id);
else :
$content = $this->view->load("content");
$content->load("clienti_form","user/add");
$this->view->render();
endif;
}
Your doing a lot wrong, starting from the fact that your doing stuff from the model in your controller, and you should divide it, otherwise your not using the concept of MVC.
Try something like this, being hard to help you, without seeing the whole code:
Model
function add_user()
{
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'indirizzo' => $this->input->post('indirizzo'),
'citta' => $this->input->post('citta'),
'cap' => $this->input->post('cap')
);
return $this->db->insert('user', $data);
}
Controller
function add() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('indirizzo', 'Indirizzo', 'required');
$this->form_validation->set_rules('citta', 'Citta', 'required');
$this->form_validation->set_rules('cap', 'Cap', 'required');
$errore = true;
if ($this->form_validation->run() === FALSE){ // if doesnt work load your view
$this->load->view('your view');
}
else {
$this->user_model->add_user();
$this->log_model->scrivi_log($user_id,"user","add");
$this->session->set_flashdata('feedback', 'User added.');
redirect("user/pageuser/".$user_id);
$content = $this->view->load("content");
$content->load("clienti_form","user/add");
$this->view->render();
}
}
You really should try and search more about it, and learn!
I could learn a lot of the basics of CodeIgniter, watching this channel that has great content, and explains every detail: https://www.youtube.com/playlist?list=PLillGF-RfqbaP_71rOyChhjeK1swokUIS
function add_user($data) {
$this->db->insert("user",$data);
$ins_id =$this->db->insert_id();
return $ins_id;
}
use this in model..
and in controller set rules for each like this
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
// for all other

password matching in codeigniter

I used to validate my registration form by the following code:
$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[cpassword]|md5');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required');
but when i browse my form it shows me an error that password doesn't match.
codeigniter form result
Controllers are not for database. So, please change your code to this:
$this->form_validation->set_rules('password', 'Password', 'trim|required');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required|matches[password]');
If you want to put it as a hash into the database, you should use Models. Here is an example code:
public function signup() {
$password = $this->input->post('password', true);
$hash = password_hash($password, PASSWORD_BCRYPT); // put $hash variable into your database
...
}

Validate characters in Codeigniter

I am developing an application in CI supported Grocery CRUD , but at the time of validation is not recognized , what I need is that a field is validated to accept only alphabetic characters , plus points , comma and space but does not work:
Function in controller
Lines of code in the function of Grocery CRUD in what I call the function solo_letras:
Lines of code in method of Grocery CRUD
What would be a validation that could take?
Use the built in form validation in CodeIgniter.
I do it like this.
At the beginning of your function set all the rules for your form inputs like this:
$this->form_validation->set_rules('inputFirstName', 'First Name', required|min_length[4]|max_length[16]|is_unique[users.username]');
This is a sample for a user name field. The first parameter is the form input name='inputFirstName', The second is a readable version of the first and is used for error reporting, then comes your validations which are separated by the pipe character. There is a validation for matching regex; regex_match[/regex/].
Place all your validations then use:
if($this->form_validation->run() == false) {
Do something here if validation fails
return false;
}
To test for validation.
Then continue on with the code if validation passes.
Here is a full sample of a simple registration function:
public function register()
{
$this->output->set_content_type('application_json');
$this->form_validation->set_rules('inputUsername', 'User Name', 'required|min_length[4]|max_length[16]|is_unique[users.username]');
$this->form_validation->set_rules('inputEmail', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('inputFirstname', 'First Name', 'required|max_length[20]');
$this->form_validation->set_rules('inputLastname', 'Last Name', 'required|max_length[20]');
$this->form_validation->set_rules('inputPassword', 'Password', 'required|min_length[6]|max_length[16]|matches[inputPasswordConfirm]');
$this->form_validation->set_rules('inputPasswordConfirm', 'Password Confirmation', 'required');
if($this->form_validation->run() == false) {
$this->output->set_output(json_encode(['result' => 0, 'error' => $this->form_validation->error_array()]));
return false;
}
$username = $this->input->post('inputUsername');
$email = $this->input->post('inputEmail');
$firstName = $this->input->post('inputFirstname');
$lastName = $this->input->post('inputLastname');
$password = $this->input->post('inputPassword');
$passwordConfirm = $this->input->post('inputPasswordConfirm');
$this->load->model('user_model');
$user_id = $this->user_model->insert([
'username' => $username,
'email' => $email,
'firstName' => $firstName,
'lastName' => $lastName,
'password' => hash('sha256', $password . PASSWORD_SALT)
]);
if($user_id) {
$this->session->set_userdata(['user_id' => $user_id]);
$this->output->set_output(json_encode(['result' => 1]));
return false;
}
$this->output->set_output(json_encode(['result' => 0, 'error' => "User not created."]));
}

Security things to do in input data

I have a website build in CodeIgniter framework. The website contain a lot of forms for different purposes. I am submitting these forms directly to a controller function.
What are the things I should apply in this input before I save it to database through the model?
If I directly send this data without doing anything, what will be the security risk?
You need to use form_validation
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
Best way will be if you will set rules for each field
like this
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
And you don't need to use any special escape
Or try to understand how to use PDO in CodeIgniter
http://codebyjeff.com/blog/2013/03/codeigniter-with-pdo

Codeigniter Signup Controller code review

I just started using a MVC framework, especially Codeigniter and i am having some trouble maintaining my code and where to place my functions(controller or model).
For now i am building a sign up system and i have a controller with the name signup.php
This is my code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Signup extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[32]');
if ($this->form_validation->run() == false){
$this->load->view("register/index");
}else{
$this->submitRegistration();
}
}
public function ajaxup(){
if ($this->input->isAjaxRequest()){
header('Content-type: application/json');
$error = false;
$message = '';
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[32]');
if ($this->form_validation->run() == false){
$message = validation_errors();
$error = true;
}else{
$this->_submitRegistration();
$message = 'Successfully registered.';
}
$return = array(
'error' => $error,
'message' => $message
);
$return = json_encode($return);
echo $return;
}
}
public function _submitRegistration(){
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$data = array(
'username' => $username,
'email' => $email,
'password' => $password
);
$this->load->model('users_model');
$this->users_model->register_user($data);
}
public function check_valid_username($username){
$this->load->model('users_model');
if (!$this->users_model->is_valid_username($username)){
$this->form_validation->set_message('check_valid_username', 'The %s field should contain only letters, numbers or periods');
return false;
}
return true;
}
}
Is there anything i could write better to maintain my code and be readable?
*NOTE:*the function ajaxup is used when a user clicks the button and does an ajax call.
Thanks
Looks pretty good to me. Here are few ideas/suggestions for future improvements:
In index() you are calling $this->submitRegistration() but I think you want to be calling $this->_submitRegistration().
Since you are using the same validation rules in both the index() and ajaxup() methods you could pull pull them out into an array and either make them a property of your controller or put them into a config file.
For documentation see here and here.
$validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
Then in your methods you would do something similar to $this->form_validation->set_rules($validation_rules).
Think about reordering your validation rules. For example, let's take a look at the rules for the username field. If check_valid_username() is making a call to the database (through the user model) then it would probably be better to validate the length requirements before. There's no use making an expensive call to the database if we can determine if the username is invalid.
Make your callback methods private. Right now check_valid_username() is a public method and could potentially be accessed through the URL. Prefix it with an underscore (_check_valid_username()) and then in your validation rules use callback__check_valid_username. Note the two underscores.
If you find yourself needing to use check_valid_username() in multiple controllers you could extend the native form validation library and put it there.
This looks fine to me. You seem to have all the relevant functions located in the user model and you are using the controller to access them. All I can suggest is read up on MVC theory if you feel unsure.
This is a good article:
http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html

Categories