How to load username & password into a database table using CodeIgniter3 format?

This is what Ive started with but I need guidance coz it does not work;

The table only has 4 columns (1) user_id (2) date_reg (3) user_name (4) pass_word

This is the Controller.

php
defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class RegisterUser extends CI_Controller
{

public function index()
{
$this->load->library(‘session’);
$this->load->helper(array(‘form’,‘url’,‘file’));

{
$this->load->view(‘registeruser’);
}
else
{
$username = $this->input->post(‘username’);
$password = $this->input->post(‘password’);

$this->load->model(‘Username_Model’, ‘username_model’);

$result = $this->username_model->insert_user($username, $password);

$userdata = array(‘user_id’ => $result);

$userdata[‘success’] = TRUE;
$userdata = $user_name;

}
}
}

And this is the Model.

php
defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class Username_Model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}

public function insert_user($username, $password)
{
$userdata = array(‘user_name’=> $username, ‘pass_word’=> $password);
$this->db->update(‘tbl_member’, $userdata);
}

public function is_name_exist($username)
{
$this->db->select(’*’);
$this->db->where(‘user_name’, $username);
$query = $this->db->get(‘tbl_member’);
if ($query->result())
return TRUE;
else
return FALSE;
}

public function is_name_pass_exist($username, $password)
{
$this->db->select(‘user_id’);
$this->db->where(‘user_name’, $username);
$this->db->where(‘pass_word’, $password);
$query = $this->db->get(‘tbl_member’);
if($query->result())
return TRUE;
else
return FALSE;
}

public function getUserInfo($username)
{
//get all info
$this->db->select(’*’);
$this->db->where(‘user_name’, $username);
$result = $this->db->get(‘tbl_member’);
$row = $result->row();
return $row;
}
}

Can somebody please correct the coding where it is wrong?

Apology if the coding is not wrapped - Everything Ive tried wont work.

Personally, I try to keep my login script simple →

// Generate a CSRF token if it doesn't exist and store it in the session
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Process the login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if the submitted CSRF token matches the one stored in the session
    if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        // Sanitize the username and password input
        $username = strip_tags($_POST['username']);
        $password = $_POST['password'];

        // Verify the user's credentials
        if ($login->verify_credentials($username, $password)) {
            // Generate a secure login token
            $token = bin2hex(random_bytes(32));
            // Store the login token in the database
            $login->store_token_in_database($_SESSION['user_id'], $token);

            // Set a secure cookie with the login token
            setcookie('login_token', $token, [
                'expires' => strtotime('+6 months'),
                'path' => '/',
                'domain' => DOMAIN,
                'secure' => true,
                'httponly' => true,
                'samesite' => 'Lax'
            ]);

            // Store the login token in the session
            $_SESSION['login_token'] = $token;

            // Redirect the user to the dashboard
            header('Location: dashboard.php');
            exit;
        } else {
            // Display an error message for invalid username or password
            $error = 'Invalid username or password';
            error_log("Login error: " . $error);
        }
    } else {
        // Display an error message
        $error = 'Invalid CSRF token';
        error_log("Login error: " . $error);
        $error = 'An error occurred. Please try again.';
    }
}

and the part of the Login class that verifies the user →

    public function verify_credentials($username, $password): bool
    {
        $sql = "SELECT id, password FROM admins WHERE username =:username LIMIT 1";
        $user = $this->retrieve_credentials($sql, $username);
        if ($user && password_verify($password, $user['password'])) {
            session_regenerate_id(); // prevent session fixation attacks
            $_SESSION['user_id'] = $user['id'];
            return true;
        }

        return false;
    }

Thanks for your effort @Strider64 & yes I agree with simplicity however I do find your script complicated, firstly due to there being no MVC format & secondly I am only familiar with Codigniter 3 which your script is incompatible with. CI3 is an old architecture & is also incampatible with CI4.

I will need to amend my post in an attempt to attract a CodeIgniter3 enthusiast for advice.

I was hoping to be able to edit my post but can not do so. Also I am unable to uncheck the “Solution” tag.

SO IS THERE A CODEIGNITER 3 ENTHUSIAST AVAILABLE?

{
$this->load->view(‘registeruser’);
}
else
{
$username = $this->input->post(‘username’);

Why is there no conditional logic above the load view section?
What errors or behavior are you seeing that makes it not work?

Also you should read this What is the most used method for hashing passwords in PHP ? - GeeksforGeeks

Thanks for your input @anaror. I do have the validation process before the load view section which works OK so I felt it was not necessary to include in this post.

I have simplified the coding a lot since the original post as follows;

This is the Controller.

php
defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class RegisterUser extends CI_Controller
{

public function index()
{
$this->load->library(‘session’);
$this->load->helper(array(‘form’,‘url’,‘file’));
$this->load->model(‘Username_model’, ‘username_model’);

{
$this->load->view(‘registeruser’);
}
else
{
$username = $this->input->post(‘username’);
$password = $this->input->post(‘password’);

/* PHPStartDelete
I have deleted the 3 lines directly below & replaced with the 1 line further below.
$result = $this->username_model->insert_user($username, $password);
$data = array(‘user_id’ => $result);
$this->session->set_userdata($data);
PHPDeleteEnd */

$this->username_model->insert_user($username, $password);

}
}
}

This is the Model.

php
defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class Username_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}

public function insert_user($username, $password)
{
$data = array(‘user_name’=> $username, ‘pass_word’=> $password);
$this->db->update(‘tbl_member’, $data);
}
}

All Im trying to achieve is to get the username & password entered into the table. But it wont enter.

At this point I tend to think there is a fault within the database coz I get an error & cant open phpmyadmin. I intend to reboot within the next few hours but do suspect when I do get phpmyadmin open my goal will still not be achieved.

Your further comments will be welcome.

I have now rebooted & the database tables are opening but I still cant get the data to enter the table. Im exhausted with ideas.

Im logging on under one database table but Im now trying to log on with a different username & password under another table. Is that the cause of the problem?

If so, how can I solve that?

Sponsor our Newsletter | Privacy Policy | Terms of Service