Codeigniter Tutorials
- What is codeigniter?
- Application_Architecture
- MVC Architecture
- HMVC Architecture
- Codeigniter Configuration
- Remove index.php from url in codeigniter
- MVC Concept
- View
- Alternate PHP Syntax for View Files
- Routing
- Codeigniter URL
- Get Current URL
- Previous page URL get
- Seo Friendly URL
- Slug Create in codeigniter
- What is _remap() function
- Remove controller name from url in codeigniter
- Codeigniter Controller Class
- Class Constructor
- GET $ POST method in Codeigniter
- Models
- Basepath, Apppath, FCPATH
- URI Segment
- Page Redirect
- Helper class
- Custom Helper class
- Form Helper
- Common Helper Functions
- Common Function
- Array Problems
- Call controller in Helper
- Add active class to menu using Helper class
- Custom Library
- Custom Library Example
- when to use get_instance()
- Codeigniter Hook
- how to work inline css in codeigniter
- Custom 404 page
- 404 custom error page
- Create custom config file in codeigniter
- How to set and get config item value
- How to Speed Up CodeIgniter App?
- Codeigniter Functions
- Session
- cookies
- How to Set & Get Tempdata in Codeigniter
- flash messages in Codeigniter
- Flashdata
- Encryption and Decryption In CodeIgniter
- Codeigniter security
- csrf token form security
- Password Hashing
- Form Validation
- Custom Validation
- Registration Form with validation
- Server Side Form Validation
- Validate Select Option Field
- Date Format Validation
- Date Format change in codeigniter
- Date Functions
- DOB Validation
- CI CRUD
- User SignUp
- User Login
- User Logout
- Login Account
- Login form with RememberMe
- Login Form with session
- User change password
- Change Password with Callback Validation to Check Old Password
- Forgot password
- Reset password
- Insert data in database
- Fetch data from database
- Update data in database
- Delete data in database
- File Upload
- Image Upload with resize Image
- Upload Multiple file and images
- Upload Multiple images with CRUD
- File and image update
- Upload Image Using Ajax.
- Email Send
- Email Send Using Email library
- Email Send Using SMTP Gmail
- Notification send
- store data in json format in DB
- Json parse
- Fetch data Using Ajax with Json data
- How to Show data Using Ajax with Json parse
- Get JSON Data from PHP Script using jQuery Ajax
- Insert data Using Ajax
- Submit data Using Ajax with form validation
- How to show data Using Ajax in codeigniter
- Insert & Update Using Ajax
- Registration Form With Validation Using Ajax in codeigniter
- Delete data Using Ajax Confirmation
- Delete All data Using checkbox selection
- Ajax CSRF Token
- Ajax Post
- Ajax serverside form validation
- Contact form using AJAX with form validation
- DataTable Using Ajax dynamically
- DataTables pagination using AJAX with Custom filter
- DataTables AJAX Pagination with Search and Sort in codeigniter
- DataTables in Codeigniter using Ajax
- Ajax Custom Serarch
- Ajax Live Data Search using Jquery PHP MySql
- Ajax Custom Serarch and sorting in datatable
- Dynamic Search Using Ajax
- Autocomplete using jquery ajax
- Jquery Ajax Autocomplete Search using Typeahead
- Dynamic Dependent Dropdown Using Ajax
- Dynamic Dependent Dropdown list Using Ajax
- Dynamic Dependent Dropdown in codeigniter using Ajax
- ajax username/email availability check using JQuery
- Check Email Availability Using Ajax
- Data Load on mouse scroll
- Ajax CI Pagination
- Pagination in codeigniter
- Ajax Codeigniter Pagination
- email exists or not using ajax with json
- CRUD using AJAX With Modal popup in CI
- Add / Show Data on modal popup using Ajax
- Modal popup Validation using Ajax
- Data show on Modal popup Using Ajax
- Add / Remove text field dynamically using jquery ajax
- How to Add/Delete Multiple HTML Rows using JavaScript
- Delete Multiple Rows using Checkbox
- Multiple Checkbox value
- Form submit using jquery Example
- REST & SOAP API
- Multi-Language implementation in CodeIgniter
- How to pass multiple array in view
- Captcha
- create zip file and download
- PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
- data export in excel sheet
- Excel File generate in Codeigniter using PHPExcel
- Dompdf library
- tcpdf library
- Html table to Excel & docs download
- CI Database Query
- Database Query
- SQL Injection Prevention
- Auth Model
- Join Mysql
- Tree View in dropdown option list
- OTP Integration in codeigniter
- curl post
- download file using curl
- Sweet Alert
- Sweet alert Delete & Success
- Log Message in Codeigniter
- Menu & Submenu show dynamically
- Set Default value in input box
- Cron Jobs
- Stored Procedure
- Display Loading Image when AJAX call is in Progress
- Send SMS
- IP Address
- Codeigniter Tutorialspoint
- Website Link
- How To Create Dynamic Xml Sitemap In Codeigniter
- Paypal Payment Integration
- Get Latitude and Longitude From Address in Codeigniter Using google map API
- How To Create Simple Bar Chart In Codeigniter Using AmCharts?
- dynamic Highcharts in Codeigniter
- Barcode in Codeigniter
- Codeigniter Interview Questions
- Project
password hashing in codeigniter.
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 :
$2y$10$pN0wQOpPE.oDzvF2mVFNzOGhzkEIEvnCg7LG4gghjNr.MZvcNMvyq
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.';
}
?>
File Name :
File Name :