password hashing in codeigniter

password hashing in php

web developer using MD5 and SHA1 algorithms to encrypt the password. But those algorithms are pretty old and not reliable now a days (So many websites are still using SHA1 and its more reliable than MD5). Its an age of advance encryption, and we need to secure our password with Password hashing is provided by PHP.


Password hashing in PHP

In PHP, php will generate the unique hash for your password every time so you need not to use your own salt and store it in database. I used this core PHP function for password hashing in my codeigniter code.

File Name :


common_helper

File Name : common_helper.php

/**
* This function used to generate the hashed password
* @param {string} $plainPassword : This is plain text password
*/
if(!function_exists('getHashedPassword'))
{
function getHashedPassword($plainPassword)
{
return password_hash($plainPassword, PASSWORD_DEFAULT);
}
}
/**
* This function used to generate the hashed password
* @param {string} $plainPassword : This is plain text password
* @param {string} $hashedPassword : This is hashed password
*/
if(!function_exists('verifyHashedPassword'))
{
function verifyHashedPassword($plainPassword, $hashedPassword)
{
return password_verify($plainPassword, $hashedPassword) ? true : false;
}
}

Controller Class

File Name : Register.php

<?php
defined('BASEPATH') OR exit('no direct script access allowed');
class Register extends CI_Controller
{
public function __construct()
{
parent::__construct();
}

public function index()
{
$data = array();
$data['title'] = "User Register";

//$this->load->view('user/header',$data);
$this->load->view('user/register');
//$this->load->view('user/footer');
}

public function user_register()
{
if($this->input->method() == 'post')
{


$this->form_validation->set_rules("user_name", "User name", "trim|required|min_length[4]|max_length[64]");
$this->form_validation->set_rules('password', 'User Password', 'trim|required|min_length[4]|max_length[20]');

$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');

$this->form_validation->set_rules("email", "EmailId", "trim|required|valid_email|is_unique[user_registers.email]|max_length[64]");
$this->form_validation->set_rules("mobile", "Mobile No", "trim|required");

if ($this->form_validation->run() == FALSE)
{
$this->load->view('user/register');
}
else
{

$user_name = ucwords(strtolower($this->input->post('user_name')));
//$password = md5($this->input->post('password'));
$password = $this->input->post('password');
$email = $this->input->post('email');
$mobile = $this->input->post('mobile');
$term_condition = $this->input->post('term_condition');
$created_at = date('Y-m-d H:i:s');

$userInfo = array(
'email' =>$email,
'user_name' =>$user_name,
'password' =>getHashedPassword($password),
'mobile' =>$mobile,
'created_at' =>$created_at,
'term_condition' =>$term_condition
);

//$result = $this->db->insert('user_registers',$data);
//redirect('user/login');

$result = $this->User_model->addNewUser($userInfo);
if($result > 0)
{
$this->session->set_flashdata('success', 'New User Registered successfully');
}
else
{
$this->session->set_flashdata('error', 'Sorry! User Registration failed');
}

redirect('user/login');






}


}
}


}

User_model

File Name : User_model.php

public function addNewUser($userInfo)
{
$this->db->trans_start();
$this->db->insert('user_registers', $userInfo);
$insert_id = $this->db->insert_id();
$this->db->trans_complete();
return $insert_id;
}

public function loginMe($user_name, $password)
{
$this->db->select('ur.user_name, ur.password, ur.email, ur.mobile');
$this->db->from('user_registers as ur');
$this->db->where('ur.user_name', $user_name);
$query = $this->db->get();
$user = $query->result();

if(!empty($user)){
if(verifyHashedPassword($password, $user[0]->password)){
return $user;
} else {
return array();
}
} else {
return array();
}
}

Login Controller

File Name : Login.php

<?php
defined('BASEPATH') OR exit('no direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();

}

public function index()
{
$data = array();
$data['title'] = "User Login";

//$this->load->view('user/header',$data);
$this->load->view('user/login');
//$this->load->view('user/footer');
}


public function login_authenticate()
{
if($this->input->method() == 'post')
{
$this->form_validation->set_rules("user_name", "User name", "trim|required");
$this->form_validation->set_rules('password', 'User Password', 'required|trim|min_length[4]|max_length[20]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('user/login');
}
else
{
$user_name = $this->input->post('user_name');
//$password = md5($this->input->post('password'));
$password = $this->input->post('password');

$result = $this->User_model->loginMe($user_name, $password);
// if(!empty($result))
if(count($result) > 0)
{
foreach ($result as $res)
{
$sessionArray = array('username'=>$res->user_name,
'email'=>$res->email,
'mobile'=>$res->mobile,
'isLoggedIn' => TRUE
);

$this->session->set_userdata($sessionArray);

// remember me
if(!empty($this->input->post("remember")))
{
setcookie ("loginId", $user_name, time()+ (10 * 365 * 24 * 60 * 60));
//setcookie ("loginPass", $password, time()+ (10 * 365 * 24 * 60 * 60));
}
else
{
setcookie ("loginId","");
setcookie ("loginPass","");
}

redirect("user/dashboard");
}
}
else
{
//$this->session->set_flashdata('error', 'Email or password mismatch');
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username and password!</div>');
redirect('user/login');
}


}



}
}




public function forgot_password()
{
$data = array();
$data['title'] = "Forgot Password";


$this->load->view('user/forgot-password');

}

public function logout()
{
$this->session->sess_destroy();

$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");

$data['logout_message'] = 'Successfully Logout';

$this->load->view('home', $data);

}


}

Password Hashing Functions

File Name :

  • password_algos( )
  • password_get_info()
  • password_hash()
  • password_needs_rehash()
  • password_verify()

  • password_algos( )

    Returns a complete list of all registered password hashing algorithm IDs as an array of strings. This function has no parameters.

    File Name :

    print_r(password_algos());

    Array
    (
    [0] => 2y
    [1] => argon2i
    [2] => argon2id
    )

    password_get_info()

    When passed in a valid hash created by an algorithm supported by password_hash(), this function will return an array of information about that hash.

    File Name :

    <?php
    $password_plaintext = "12345";
    $password_hash = password_hash( $password_plaintext, PASSWORD_DEFAULT, [ 'cost' => 11 ] );
    print_r( password_get_info( $password_hash ) );


    ?>


    /* returns:
    Array (
    [algo] => 1
    [algoName] => bcrypt // Your server's default.
    [options] => Array ( [cost] => 11 )
    )
    */

    password_hash()

    password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

    File Name :


    password_needs_rehash()

    File Name :

    <?php

    $password = 'rasmuslerdorf';
    $hash = '$2y$10$YCFsG6elYca568hBi2pZ0.3LDL5wjgxct1N8w/oLR/jfHsiQwCqTS';

    // The cost parameter can change over time as hardware improves
    $options = array('cost' => 11);

    // Verify stored hash against plain-text password
    if (password_verify($password, $hash)) {
    // Check if a newer hashing algorithm is available
    // or the cost has changed
    if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) {
    // If so, create a new hash, and replace the old one
    $newHash = password_hash($password, PASSWORD_DEFAULT, $options);
    }

    // Log user in
    }
    ?>

    password_verify ( string $password , string $hash )

    Verifies that the given hash matches the given password.

    File Name :

    <?php
    // See the password_hash() example to see where this came from.
    $hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

    if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }
    ?>

    what is difference between hash and encript.

    A hashing function takes a string and converts it to an encrypted format of the string is known as a hash. the formated string is like 9c84vg7baa2sdfasf56346323f464954940f8dfgd59bcf233.

    Hashing is a one-way function. when you hash something, you get a fixed-length string that can’t be easily reversed.

    encryption funtion take an input string and convert it into a random string of numbers and letters. encryption is a reversible process.


    Salting

    Salting is the action of adding a random string to a password before hashing it.


    password_hash() and password_verify()

    The password_hash() function also takes care of salting the password.

    <?php
    $password = "ittutorial";
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    if (password_verify($password, $hashed_password)) {
    //True. if the entered password matches the hashed password
    } else {
    //False. redirect to the homepage
    }

    ?>





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here