Codeigniter - form_validation callback function error message - php

View:
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<form method="post" action="<?php echo base_url();?>account/register">
<?php $form_error = $this->session->flashdata('error'); ?>
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" name="username" type="input">
<div id="form_error"><?php echo $form_error['username']; ?></div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" id="password" name="password" type="password">
<div id="form_error"><?php echo $form_error['password']; ?></div>
</div>
<div class="form-group">
<label for="confirm_password">Confirm Password</label>
<input class="form-control" id="confirm_password" name="confirm_password" type="password">
<div id="form_error"><?php echo $form_error['confirm_password']; ?></div>
</div>
<div class="form-group">
<label for="gender">Gender</label>
<select class="form-control" id="gender" name="gender">
<option disabled selected value="">select a gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<div id="form_error"><?php echo $form_error['gender']; ?></div>
</div>
<div class="form-group">
<label for="birthdate">Birthdate</label>
<input class="form-control" id="birthdate" name="birthdate" type="date">
<div id="form_error"><?php echo $form_error['birthdate']; ?></div>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="text-center">
<a class="d-block small mt-3" href="<?php echo base_url();?>pages/login_user">Already have an account?</a>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
Account Controller:
public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date');
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d',time()),
'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}
//form_validation callback
public function valid_date($birthdate){
echo 'aw';
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{
echo $birthdate;
$this->form_validation->set_message('valid_date', 'Invalid Birthdate');
$form_error['birthdate'] = form_error('valid_date');
$this->session->set_flashdata('error',$form_error);
return FALSE; }
}
Pages Controller:
public function login_user(){
$data['title'] = 'Login';
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/login');
$this->load->view('template/footer');
}
public function register_user(){
$data['title'] = 'Register';
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/registration');
$this->load->view('template/footer');
}
I tried setting flashdata inside the callback function but this is my first time using a callback function to check the validity of the birthdate given. I tested out the input and you can't input any alphabets but you can go over the maximum length. For example the format should be 'YYYY-MM-DD' you can input something like this: 555555-55-55.
All my other error prints out successfully but the valid_date callback function prints an error:
Unable to access an error message corresponding to your field name
Birthdate.(valid_date)
If what i'm asking for is impossible/wrong then i'll just add a min_length[10] and max_length[10] and just edit its error to 'invalid date'.
EDIT: Taking inspiration from my statement above about the max and min length, i also added a custom error for the valid_date there and what do you know it works.
Heres my updated controller:
public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date',
array('valid_date' => 'Invalid Date of birth'));
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d',time()),
'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}
//form_validation callback
public function valid_date($birthdate){
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{return FALSE; }
}
I'm still not sure if it really works or just by fluke.

Register code:
public function register() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');
if ($this->form_validation->run() == FALSE) {
// let's see what's going on under the hood...
print_r($this->form_validation->error_array());
exit;
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
} else {
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'), PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d', time()),
'last_login' => mdate('%Y-%m-%d', time()));
if ($this->account_model->create_account($data)) {
$this->session->set_flashdata('message', 'Registration Successful');
redirect('pages/login_user');
} else {
$this->session->set_flashdata('message', 'Registration Failed');
redirect('pages/register_user');
}
}
}
Referencing a callback necessitates the function be called via callback_func_name.
Revised callback:
Note: item does not start with callback_
See: Correctly determine if date string is a valid date in that format (read: test cases)
public function valid_date($date) {
$format = 'Y-m-d';
$d = DateTime::createFromFormat($format, $date);
if ($d && $d->format($format) == $date) {
return TRUE;
} else {
$this->form_validation->set_message('valid_date', 'Invalid Birthdate.');
return FALSE;
}
}
Doing date('YYYY-MM-DD') is wrong as it yields: 2018201820182018-FebFeb-SatSat. See date docs.

You should call this way:
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');

hey try this to use callback
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_validdate',
//form_validation callback
public function validdate($birthdate){
$birthdate = $this->input->post('birthdate');
if( date('YYYY-MM-DD',strtotime($birthdate)) )
{
return true;
}
$this->form_validation->set_message('validdate','Check the birthday input to match a format like this YYYY-MM-DD');
return false;
}
Callbacks: Your own Validation Methods
The validation system supports callbacks to your own validation methods. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback method that does that
More Detail read https://codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

Related

am i using the password-hash/password-verify wrong on Codeigniter4

im currently learning how to make a working multi level login using code igniter using multi table because every type of user have some uniqueness and i tried to use md5 in the past but someone tell me that md5 is not save, so i try to use password-hash/password-verify but when i try to fill the login form it just telling me that the password is wrong even though i fill it with the same password "123456789" when create the account
This is my AuthController
namespace App\Controllers;
use App\Models\AdminModel;
use App\Models\GuruModel;
use App\Models\MuridModel;
use App\Models\WalimuridModel;
class Auth extends BaseController
{
public function __construct()
{
$this->adminModel = new AdminModel();
$this->guruModel = new GuruModel();
$this->muridModel = new MuridModel();
$this->walimuridModel = new WalimuridModel();
$this->validation = \Config\Services::validation();
$this->session = \Config\Services::session();
}
public function valid_login()
{
//Take data from the login form
$nama_user = $this->request->getVar('username');
$password = $this->request->getVar('password');
//Take data from database that have the same username
$admin = $this->adminModel->where('username_admin', $nama_user)->first();
$guru = $this->guruModel->where('username_guru', $nama_user)->first();
$murid = $this->muridModel->where('username_murid', $nama_user)->first();
$walimurid = $this->walimuridModel->where('username_walimurid', $nama_user)->first();
//check if username founded
if($admin){
$verify_pass = password_verify($password, $admin['password_admin']);
if($verify_pass){
$sessLogin = [
'isLogin' => true,
'username' => $admin['username_admin'],
'password' => $admin['password_admin'],
'email' => $admin['email_admin'],
'nama' => $admin['nama_admin'],
'jeniskelamin' => $admin['jenis_kelamin'],
'fotoprofil' => $admin['foto_profile'],
'level' => 'admin'
];
$this->session->set($sessLogin);
return redirect()->to('/admin/index');
}
else {
session()->setFlashdata('password', 'Password salah');
return redirect()->to('/login');
}
}
else if($guru){
if($guru['password_guru'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'username' => $guru['username_guru'],
'password' => $guru['password_guru'],
'email' => $guru['email_guru'],
'nama' => $guru['nama_guru'],
'jeniskelamin' => $guru['jenis_kelamin'],
'fotoprofil' => $guru['foto_profile'],
'level' => 'guru'
];
$this->session->set($sessLogin);
return redirect()->to('/guru/index');
}
}
else if($murid){
if($murid['password_murid'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'nisn' => $murid['nisn'],
'username' => $murid['username_murid'],
'password' => $murid['password_murid'],
'email' => $murid['email_murid'],
'nama' => $murid['nama_murid'],
'jeniskelamin' => $murid['jenis_kelamin'],
'fotoprofil' => $murid['foto_profile'],
'level' => 'murid'
];
$this->session->set($sessLogin);
return redirect()->to('/murid/index');
}
}
else if($walimurid){
if($walimurid['password_walimurid'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'username' => $walimurid['username_walimurid'],
'password' => $walimurid['password_walimurid'],
'email' => $walimurid['email_walimurid'],
'nama' => $walimurid['nama_walimurid'],
'nisnanak' => $walimurid['nisn_murid'],
'jeniskelamin' => $walimurid['jenis_kelamin'],
'fotoprofil' => $walimurid['foto_profile'],
'level' => 'walimurid'
];
$this->session->set($sessLogin);
return redirect()->to('/walimurid/index');
}
}
else{
//jika username tidak ditemukan, balikkan ke halaman login
session()->setFlashdata('username', 'Username tidak ditemukan');
return redirect()->to('/login');
}
}
this is my Admin Model
<?php
namespace App\Models;
use CodeIgniter\Model;
class AdminModel extends Model
{
protected $table = 'admin';
protected $primaryKey = 'id_admin';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ["id_admin","username_admin","password_admin","email_admin","nama_admin","jenis_kelamin","foto_profile"];
}
every model is basically the same
this is my login.php (login form)
<form method="post" action="/auth/valid_login">
<div class="wrap">
<input type="username" name="username" class="input" placeholder="username">
<span class="underline"></span><br>
<?php if($username){ ?>
<div class="alert alert-danger" role="alert">
<?php echo $username?>
</div>
<?php } ?>
</div>
<div class="wrap">
<input type="password" name="password" class="input" placeholder="Password">
<span class="underline"></span><br>
<?php if($password){ ?>
<div class="alert alert-danger" role="alert">
<?php echo $password?>
</div>
<?php } ?>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn-a">Login</button>
</div>
</form>
this is my create admin form
<form method="post" action="/admin/save_admin">
Username: <br>
<input type="text" name="username" required><br>
Password: <br>
<input type="password" name="password" required><br>
Email: <br>
<input type="email" name="email" required><br>
Nama: <br>
<input type="text" name="nama_admin" required><br>
Jenis Kelamin: <br>
<input type="text" name="jenis_kelamin" required><br>
Foto Profil: <br>
<input type="text" name="fotoprofil" required><br>
<button type="submit">Register</button>
</form>
and my create function
public function save_admin()
{
$data = $this->request->getPost();
$this->validation->run($data, 'cradmin');
$errors = $this->validation->getErrors();
if($errors){
session()->setFlashdata('error', $errors);
return redirect()->to('/admin/admin/create');
}
$password = password_hash($data['password'], PASSWORD_DEFAULT);
$this->adminModel->save([
'username_admin' => $data['username'],
'password_admin' => $password,
'email_admin' => $data['email'],
'nama_admin' => $data['nama_admin'],
'jenis_kelamin' => $data['jenis_kelamin'],
'foto_profile' => $data['fotoprofil'],
]);
session()->setFlashdata('add', 'Data Admin berhasil dibuat');
return redirect()->to('/admin/admin/index');
}
i have tried to change the requirement of login like if the password same as the database it will make session or if password wrong go to login form and make session and none of it work sorry if my english is bad

Query builder update() codeigniter 4 not updateing my password

i'd like to ask some question. I want to make a change password feature in codeigniter 4, so i have to updateing my old password, but when i do that, the password it's not updated, but all my flashdata works perfectly. I also try a normal sql query but not work too.
Where is my mistake?
When i var_dump the new hash password, the new password is hashed, but again not updating my database.
This is my model
protected $user = 'user';
public function EditKataSandi($password_hash = null){
$session = \Config\Services::session();
$id = $session->get('id');
$db = \Config\Database::connect();
$builder = $db->table($this->user);
//$queryB = "UPDATE `user` SET `sandi` = $password_hash WHERE `id` = $id
//";
// $menu = $db->query($queryB);
// return $menu;
$builder->set('sandi', $password_hash);
$builder->where('id', $id);
return $query = $builder->update();
}
my controller
protected $helpers = ['form', 'url', 'array'];
public function katasandi($page = 'katasandi'){
$request = \Config\Services::request();
$validation = \Config\Services::validation();
$model = new Model_all();
$email = $this->session->get('email');
if (!$email){
return redirect()->to(base_url('/auth'));
}else{
$userAccess = $model->Tendang();
if ($userAccess < 1) {
return redirect()->to(base_url('/auth/blokir'));
}
}
if (! is_file(APPPATH.'/Views/admin/admin-katasandi/v_katasandi.php'))
{
// Whoops, we don't have a page for that!
throw new \CodeIgniter\Exceptions\PageNotFoundException($page);
}
if($request->getMethod() == 'post'){
$validation->setRules([
'katasandi_sebelum' => [
'label' => 'Kata sandi sebelum',
'rules' => 'required|trim',
'errors' => [
'required' => 'Harus diisi harus diisi!'
]
],
'katasandi_baru' => [
'label' => 'Sandi Baru',
'rules' => 'required|trim|min_length[6]|matches[katasandi_baru1]',
'errors' => [
'required' => 'Harus diisi!',
'matches' => '',
'min_length' => 'Terlalu pendek!'
]
],
'katasandi_baru1' => [
'label' => 'Sandi Ulangi',
'rules' => 'required|trim|min_length[6]|matches[katasandi_baru]',
'errors' => [
'required' => 'Harus diisi!',
'matches' => 'Harus sesuai dengan kata sandi baru!',
'min_length' => ''
]
]
]);
}
$data['nama'] = $model->GetNama();
$data['title'] = ucfirst('Ubah Kata Sandi'); // Capitalize the first letter
$data['user'] = $model->UserLogin();
$data['menu'] = $model->MenuAll();
$data['attr'] = ['id' => 'katasandi', 'name'=>'katasandi'];
if($validation->withRequest($this->request)->run() == FALSE){
echo view('admin/admin-base-html/v_header', $data);
echo view('admin/admin-base-html/v_navbar', $data);
echo view('admin/admin-base-html/v_sidebar');
echo view('admin/admin-katasandi/v_katasandi', ['validation' => $validation,'session' => $this->session]);
echo view('admin/admin-base-html/v_footer');
echo view('admin/admin-base-html/v_js');
echo view('admin/admin-katasandi/v_js_katasandi');
}else{
$pass_sebelum = $request->getPost('katasandi_sebelum');
$pass_baru = $request->getPost('katasandi_baru');
if (!password_verify($pass_sebelum, $data['user']['sandi'])) {
$this->session->setFlashdata('salah', 'Kata sandi sebelumnya salah!');
return redirect()->to(base_url('/pengguna/katasandi'));
}else{
if ($pass_sebelum == $pass_baru) {
$this->session->setFlashdata('sama', 'Kata sandi baru tidak boleh sama dengan kata sandi sebelumnya!');
return redirect()->to(base_url('/pengguna/katasandi'));
}else{
$password_hash = password_hash($pass_baru, PASSWORD_DEFAULT);
$model->EditKataSandi($password_hash);
$this->session->setFlashdata('pesan', 'Kata sandi berhasil diubah!');
return redirect()->to(base_url('/pengguna/katasandi'));
}
}
}
}
my view
<div class="col-sm-12 col-md-12 col-lg-12">
<?php echo form_open(base_url().'/pengguna/katasandi', $attr); ?>
<?php echo csrf_field(); ?>
<div class="card card-primary">
<div class="card-header">
<h4>Ubah kata sandi</h4>
</div>
<div class="card-body">
<div class="row">
<div class="form-group col-lg-12 col-sm-12 col-md-12">
<label for="katasandi_sebelum">Kata sandi sebelumnya</label>
<input type="password" class="form-control" id="katasandi_sebelum" name="katasandi_sebelum"
placeholder="" autofocus>
<label class="text-danger"><?php echo $validation->showError('katasandi_sebelum') ?></label>
</div>
<div class="form-group col-lg-6 col-sm-12 col-md-6">
<label for="katasandi_baru">Kata sandi baru</label>
<input type="password" class="form-control" id="katasandi_baru" name="katasandi_baru" placeholder="">
<label class="text-danger"><?php echo $validation->showError('katasandi_baru') ?></label>
</div>
<div class="form-group col-lg-6 col-sm-12 col-md-6">
<label for="katasandi_baru1">Ulangi kata sandi baru</label>
<input type="password" class="form-control" id="katasandi_baru1" name="katasandi_baru1"
placeholder="">
<label class="text-danger"><?php echo $validation->showError('katasandi_baru1')?></label>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary"> Ubah Kata Sandi</button>
</div>
</div>
<?php echo form_close(); ?>
</div>
and my database structure
I found my mistake, its work when i put my update password code into a new function...
Example:
Public function updatepassword(){
$data['user'] = $model->UserLogin();
$pass_sebelum = $request->getPost('katasandi_sebelum');
$pass_baru = $request->getPost('katasandi_baru');
if (!password_verify($pass_sebelum, $data['user']['sandi'])) {
$this->session->setFlashdata('salah', 'Kata sandi sebelumnya salah!');
return redirect()->to(base_url('/pengguna/katasandi'));
}else{
if ($pass_sebelum == $pass_baru) {
$this->session->setFlashdata('sama', 'Kata sandi baru tidak boleh sama dengan kata sandi sebelumnya!');
return redirect()->to(base_url('/pengguna/katasandi'));
}else{
$password_hash = password_hash($pass_baru, PASSWORD_DEFAULT);
$model->EditKataSandi($password_hash);
$this->session->setFlashdata('pesan', 'Kata sandi berhasil diubah!');
return redirect()->to(base_url('/pengguna/katasandi'));
}
}
Use $allowedFields.
This array should be updated with the field names that can be set during save, insert, or update methods. Any field names other than these will be discarded. This helps to protect against just taking input from a form and throwing it all at the model, resulting in potential mass assignment vulnerabilities. protected $allowedFields = ['name', 'email'];
You can read more in the official documentation: https://codeigniter.com/user_guide/models/model.html#models

Upload File Codeigniter,can't detect variabel

I'm trying to make upload image function on Codeigniter. but, when I trying to insert the image to the database. the variable can't be detected.
Here is my controller :
public function registrasi() {
//VALIDATION
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[tb_m_user.email]');
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[3]|matches[konfirmasi_password]');
$this->form_validation->set_rules('konfirmasi_password', 'Retype Password', 'required|trim|matches[password]');
if($this->form_validation->run() == false) {
$this->session->set_flashdata('fail' , 'Registration Failed! Please Try Again');
$this->load->view('auth/registrasi');
}else{
//INSERT TO DATABASE
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
$pict = $_FILES['pict'];
//LIBRARY UPLOAD CONFIG
$config['upload_path'] = '/assets/dist/foto_validasi';
$config['allowed_types'] = 'jpg|png';
$config['file_name'] = date('ymd');
$this->load->library('upload', $config);
if(!$this->upload->do_upload('pict')){
echo "Upload Failed";
}else{
$pict = $this->upload->data('file_name');
}
$data = [
'user_name' => $username,
'email' => $email,
'password' => $password,
'role' => 'pengguna',
'img' => $pict,
'status_aktivasi' => 'tidak aktif',
'created_by' => 'SYSTEM',
];
$this->m_auth->registrasi($data, 'tb_m_user');
$this->session->set_flashdata('success' , 'Registration Successful! Please Login');
Redirect('Auth/login');
}
}
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('auth/login');
}else{
$this->postlogin();
}
}
Here is my form View :
<?= form_open_multipart('Auth/registrasi'); ?>
<div class="border-top mt-3">
<div class="ml-2">
<label class="mt-2">Upload Kartu Identitas</label>
</div>
<div class="input-group mb-3">
<input type="file" class="form-control" placeholder="Upload Foto Identitas" name="pict">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-file-image"></span>
</div>
</div>
</div>
<small class="text-danger"><?= form_error('foto') ?></small>
</div>
<?= form_close(); ?>
Here is the error : error
I even tried to change the variabel from:
$pict = $this->upload->data('file_name');
'img' => $pict,
to :
$pict2 = $this->upload->data('file_name');
'img' => $pict2,
but it gets another error :error2
If you want the upload feature to be required, you could modify the codes like this :
public function registrasi() {
//VALIDATION
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[tb_m_user.email]');
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[3]|matches[konfirmasi_password]');
$this->form_validation->set_rules('konfirmasi_password', 'Retype Password', 'required|trim|matches[password]');
if($this->form_validation->run() == false) {
$this->session->set_flashdata('fail' , 'Registration Failed! Please Try Again');
$this->load->view('auth/registrasi');
}else{
//INSERT TO DATABASE
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
$pict = $_FILES['pict'];
//LIBRARY UPLOAD CONFIG
$config['upload_path'] = '/assets/dist/foto_validasi';
$config['allowed_types'] = 'jpg|png';
$config['file_name'] = date('ymd');
$this->load->library('upload', $config);
if(!$this->upload->do_upload('foto')){
echo "Upload Failed";
$this->session->set_flashdata('fail', $this->upload->display_errors() );
redirect( 'auth/registrasi' );
}else{
$pict = $this->upload->data('file_name');
$data = [
'user_name' => $username,
'email' => $email,
'password' => $password,
'role' => 'pengguna',
'img' => $pict,
'status_aktivasi' => 'tidak aktif',
'created_by' => 'SYSTEM',
];
$this->m_auth->registrasi($data, 'tb_m_user');
$this->session->set_flashdata('success' , 'Registration Successful! Please Login');
Redirect('Auth/login');
}
}
}
The $this->upload->display_errors() code will display the error message on the uploaded file that does not meet the requirements, so if the file is not uploaded then the registration data will not be saved.
Change the post field name as if(!$this->upload->do_upload('pict')){
if(!$this->upload->do_upload('pict')){ // You should change this
size attribute should be there in input field
<input type="file" size="1" class="form-control" placeholder="Upload Foto Identitas" name="pict">

Login verification codeigniter

My users table:
user_id PK
username
password
date_created
View:
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<?php
$message = $this->session->flashdata('message');
$form_error = $this->session->flashdata('error');
?>
<div class="lg-md-2" align="center"><?php if(isset($message)){ echo $message; }?></div>
<form method="post" action="<?php echo base_url();?>account/login">
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" name="username" type="text">
<div id="form_error"><?php echo $form_error['username']; ?></div>
</div>
<div class="form-group">
<label for="Password">Password</label>
<input class="form-control" id="password" name="password" type="password">
<div id="form_error"><?php echo $form_error['password']; ?></div>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="text-center">
<a class="d-block small mt-3" href="<?php echo base_url();?>pages/register_user">Register an Account</a>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
Controller:
public function login(){
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'));
$this->session->set_flashdata('error',$form_error);
redirect('pages/login_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => $this->input->post('password'));
$result = $this->account_model->login_account($data);
if($result ){
$new_session = array('username' => $result,
'is_logged_in' => TRUE);
$this->session->set_userdata($new_session);
//redirect('pages/view_home');
}else{
$message = $this->session->set_flashdata('message', 'Incorrect Password');
redirect('pages/login_user');
}}
}
Model:
public function login_account($data){
$query = $this->db->get_where('users', array('username' => $data['username']))->result();
if($query){
foreach($query as $row){
if(password_verify($data['password'], $row->password)){
return $row->username;}else{ return FALSE;}}
}else{ return FALSE; }
}
My question is, I wanted to be specific when the function fails if its incorrect password or if the username does not exist.
In my model, both scenario i returned FALSE. or do i have to return string? as in, return 'username' for invalid username and return 'password' for incorrect password and simply change the if statement in my controller to match that and send the appropriate message.
Or is there a better way? I keep getting reminded of try catch but i haven't really used that so if its that a better way then i'll do it but can someone post a code for it here as a reference.
Or is it simply best not to be specific about it and just input the message as 'invalid username/password' for both instances and let the user figure it out?
It's not correct to hint the user specifically, that his username or the password is incorrect. If you refer famous websites like google or facebook, they won't tell you which one is incorrect. So try to show error as Username or password are incorrect.

Codeigniter- How to preserve form values if error on submit

I have the form field like
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php if($user->postal_code === NULL) { echo set_value('postal_code');} else { echo $user->postal_code;} ?>">
<label for="form_control_1">Postal Code</label>
<span class="help-block">Postal Code is required</span>
and my function is
public function postProfile() {
if ($_POST) {
$this->form_validation->set_rules('postal_code', 'Postal Code', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('country', 'Country', 'required');
$this->form_validation->set_rules('month', 'Month', 'required');
$this->form_validation->set_rules('day', 'Day', 'required');
$this->form_validation->set_rules('year', 'Year', 'required');
$this->form_validation->set_rules('mobile_number', 'Mobile Number', 'required');
if ($this->form_validation->run() === FALSE) {
//$this->session->set_flashdata('err', validation_errors());
$this->session->set_flashdata('email_err', form_error('email'));
$this->session->set_flashdata('postal_code_err', form_error('postal_code'));
$this->session->set_flashdata('gender_err', form_error('gender'));
$this->session->set_flashdata('country_err', form_error('country'));
$this->session->set_flashdata('day_err', form_error('day'));
$this->session->set_flashdata('year_err', form_error('year'));
$this->session->set_flashdata('month_err', form_error('month'));
$this->session->set_flashdata('mobile_err', form_error('mobile_number'));
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
$dob = $this->input->post('month') . '/' . $this->input->post('day') . '/' . $this->input->post('year');
$userData = array(
'email' => $this->input->post('email'),
'date_of_birth' => $dob,
'gender' => $this->input->post('gender'),
'country' => $this->input->post('country'),
'mobile_number' => $this->input->post('mobile_number'),
'postal_code' => $this->input->post('postal_code'),
);
$updateUser = $this->user->updateUser($this->session->userdata['front']['id'], $userData);
if ($updateUser) {
$this->session->set_flashdata('err', '<div class="alert alert-success">Profile Updated Successfuly</div>');
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
echo "Un expected error ";
exit;
}
}
} else {
$this->logout();
}
}
but value is not shown for the postal code field in case of validation errors
When error occur then you need to render view instead of rediect().
if ($this->form_validation->run() == FALSE) {
// no need to set_flashdata here for form_error()
$this->load->view('view_form',$data);
return;
}else{
//success code
}
Now view file
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php echo set_value('postal_code');?>">
<?php echo form_error('postal_code','<p class="alert alert-danger">','</p>');?>
Now your form will repopulate previous data if any error occur. In the same time you will see error message under your postal_code field
You can set these values in flashdata and redirect to your form. For example
if ($this->form_validation->run() == FALSE) {
$data = array(
'errors' => validation_errors(),
'name' => $this->input->post('name')//check this
);
$this->session->set_flashdata($data);
redirect('YOUR-URL-HERE');
}
And in your form use value attribute of form input as given below
<input type="text" class="form-control" name="name" placeholder="Name" value="<?= $this->session->flashdata('name'); ?>">

Categories