Codeigniter Signup Controller code review - php

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

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

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."]));
}

How to send post values in RESTful API using CodeIgniter?

I don't have any idea how to get values please help me to sort this problem. Tell me with a reference if someone already has the code then please share. I'm also curious as how to load spark with cURL with a RESTful API with full procedure
<?php class LoginController extends CI_Controller {
public function index()
{
$this->load->view('admin/header');
$this->load->view('admin/index');
$this->load->view('admin/footer');
}
public function loginCon(){
$this->load->Library('rest');
$this->form_validation->set_rules('email', 'E-mail', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters("<p class='text-danger'>", "</p>");
if ($this->form_validation->run()==false)
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->session->set_flashdata('login_failed', 'Invalid User Name Password');
}else{
$config = array('server' => "http://api.amid.tech/hsApiV2/api/demo.php/",
'http_user' => 'admin',
'http_pass' => 'xxxxx',
'http_auth' => 'basic',
);
$this->rest->initialize($config);
$method = 'post';
$param = array(
'UserEmail' => $this->input->post('email'), // works fine here
'UserPass' => $this->input->post('password'),
'UserRoleId'=>1
);
$uri = 'adminlogin';
$this->rest->format('application/json');
$result = $this->rest->{$method}($uri, $param);
echo $result;
$this->load->view('admin/admin_header');
$this->load->view('admin/sidebar');
$this->load->view("admin/dashboard");
$this->load->view('admin/dashboard.php');
}
}
public function registerd()
{
$this->load->view('admin/header');
$this->load->view('admin/registration');
$this->load->view('admin/footer');
}
} ?>
To get raw inputs try
// get the raw POST data
$rawData = file_get_contents("php://input");
For validation try
$this->form_validation->set_rules($rawData['email'], 'E-mail', 'required|trim');

Can one use inline validation rules, and config file based validation rules simultaneously?

PHP / CodeIgniter.
In order to set up a form that validates the logic: "either one, or both, of the fields is required" I have to use inline form validation like this (source is http://ellislab.com/forums/viewthread/136417/#672903):
if ( ! $this->input->post('email'))
{
$this->form_validation->set_rules('phone', 'Phone Number', 'required');
}
else
{
$this->form_validation->set_rules('phone', 'Phone Number', '');
}
// If no phone number, email is required
if ( ! $this->input->post('phone'))
{
$this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
}
else
{
$this->form_validation->set_rules('email', 'Email Address', 'valid_email');
}
But I have a whole lot of other forms where I'd prefer to use config file based form validation.
I cannot think of a way to get the two to co-exist, and I don't really want to now go and bring all my rules into the code body.
Any suggestions?
You can use rule sets from the config file or inline rules just fine in the same application.
config/form_validation.php
$config = array(
'ruleset1' => array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|trim|alpha'
),
)
);
controller example
public function ruleset()
{
if ($this->input->post())
{
// runs validation using ruleset1 from the config
if ($this->form_validation->run('ruleset1') == FALSE)
{
...
}
}
}
public function inline_rules()
{
if ($this->input->post())
{
// ignores the config and uses the inline rules
$this->form_validation->set_rules('username', 'Username', 'required|trim|alpha_numeric');
if ($this->form_validation->run() == FALSE)
{
...
}
}
}
Note: I found that trying to mix them for the same form does not work. Specifying inline rules and a ruleset on the same form will cause the ruleset to be ignored completely and the inline rules to be applied.
Create a file in your libraries name it MY_Form_validation
class MY_Form_validation extends CI_Form_validation
{
public function __construct($rules = array())
{
parent::__construct($rules);
$this->CI->lang->load('MY_form_validation');
}
function email_phone($str)
{
if(!$str)
{
// if POST phone exists validate the phone entries
//validation for phone
return TRUE;
}else{
//if no phone was entered
//check the email
$email = $this->input->post('email'));
//use the systems built in validation for the email
//set your error message here
return $this->valid_email($email) && $this->required($email);
}
}
}
//or set the message here
$this->form_validation->set_message('email_phone','Please enter either an email or phone.');
$this->form_validation->set_rules('phone', 'Phone Number', 'email_phone');

How to access data from form validating controller in codeigniter?

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.

Categories