This program will let you login first then what I need to do is to have something like edit their profile/info. I cannot fetch the data from the database, when I click the page for profile and nothing is shown.
MODEL
function login($username, $password) {
$this->db->select('username, password');
$this->db->from('tblsec');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
public function get_id($username) {
$query = $this->db->query("SELECT * from tblsec WHERE username = '$username'");
$r = $query->result();
return $r;
}
VIEW
<?php foreach ($username as $user): ?>
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-5">
<?php echo $user->firstname; ?> <?php echo $user->lastname; ?>
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Password</label>
<div class="col-sm-5">
**********
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-5">
<?php echo $user->lastname; ?>
</div>
</div>
<br>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-5">
<?php echo $user->email; ?>
</div>
</div>
<br>
<?php endforeach; ?>
</div>
</div>
CONTROLLER
function __construct() {
parent::__construct();
$this->load->model('secretary_model', '', TRUE);
$this->load->library('form_validation');
$this->load->helper('date');
}
public function index() {
if ($this->session->userdata('logged_in')) {
$this->header();
$this->load->view('secretary/sec_login_view');
} else {
redirect('secretary/sec_login_view');
}
}
public function profile() {
if ($this->session->userdata('logged_in')) {
$username = $this->session->userdata('username');
$data['username'] = $this->secretary_model->get_ID($username);
$this->header2();
$this->load->view('secretary/secretary_profile', $data);
} else {
redirect('secretary/login', 'refresh');
}
}
First of all, Make sure you have set the logged_in session, that will ensure that the user is logged in or not. Something like
// After checking the username and password
$this->session->set_userdata('logged_in', true);
Second If username or related data not found then return the false or appropriate error in model.
/**
*#return mixed object|false
*/
function get_id($username) {
$query = $this->db->query("SELECT * from tblsec WHERE username = '$username'");
return $query->num_rows() > 0 ? $query->result() : false;
}
Then check in your view value in your view like this:
if( is_array($username) && count($username) > 0 ) {
foreach ($username as $user):
// Set data accordingly
endforeach;
}
else {
echo "Sorry! Related Data not found!";
}
Its a good approach to fetch and debug things accordingly.
Related
I'm trying to create some admin login. I think my code is correct because when I input wrong email and password the error message appears on login page. However, when I input correct data of my DB, it also shows error message.
Please help me. I appreciate any answer.
my controller (Admin.php):
public function index()
{
$this->admindashboard();
}
public function admindashboard()
{
$data = array();
/* $data['main_content'] = $this->load->view('admin_main', '', TRUE); */
$this->load->view('admin/admin_main', $data);
}
public function admin_regst()
{
$data = array();
$data['main_content'] = $this->load->view('admin-regist', '', TRUE);
$this->load->view('admin/admin_main', $data);
}
My other controller (Login_admin.php):
public function index()
{
$this->load->view('login');
}
public function adminchecklogin()
{
$data = array();
$adminemail = $this->input->post('admin_email', TRUE);
$adminpassword = $this->input->post('admin_psw', TRUE);
$this->load->model('M_login_admin');
$admindetails = $this->M_login_admin->admin_login_check($adminemail);
if (password_verify($adminpassword, $admindetails->admin_psw)) {
if ($admindetails->admin_status == 1) {
$session_data['adminid'] = $admindetails->admin_id;
$session_data['adminemail'] = $admindetails->admin_email;
$session_data['adminusername'] = $admindetails->admin_username;
$session_data['adminstatus'] = $admindetails->admin_status;
$this->session->set_userdata($session_data);
redirect('Admin');
} else {
$data['error_msg'] = "User ini tidak aktif....!!!";
redirect('login', $data);
}
} else {
redirect('error-login', $data);
}
}
public function login_error()
{
$data['error_msg'] = "Email atau Password Anda Salah....!!!";
$this->load->view('login', $data);
}
my model (M_login_admin.php):
public function admin_login_check($adminemail)
{
$admin_details = $this->db->select('*')
->from('admin')
->where('admin_email', $adminemail)
->get()
->row();
return $admin_details;
}
my view(login.php):
<body>
<section class="hero is-fullheight">
<div class="hero-body container has-text-centered">
<div class="login">
<img src="https://logoipsum.com/logo/logo-1.svg" width="325px" />
<p>
<?php
if (isset($success_msg)) {
echo $success_msg;
}
?>
</p>
<p>
<?php
if (isset($error_msg)) {
echo $error_msg;
}
?>
</p>
<form action="<?= base_url(); ?>Login_admin/adminchecklogin" method="POST">
<div class="box">
<div class="field">
<div class="control">
<input class="input is-medium is-rounded" type="email" placeholder="hello#example.com" autocomplete="username" name="admin_email" required />
</div>
</div>
<div class="field">
<div class="control">
<input class="input is-medium is-rounded" type="password" placeholder="**********" autocomplete="current-password" name="admin_psw" required />
</div>
</div>
<div class="field has-text-left ml-3 mt-5">
<label class="checkbox">
<input type="checkbox">
Remember me
</label>
</div>
</div>
<button class="button is-block is-fullwidth is-primary is-medium is-rounded" type="submit">
Login
</button>
</form>
<br>
</div>
</div>
</section>
My route
DB Column
DB Data
Interface
Your database has the admin_psw in plain text that would explain why the password_verify() is failing.
In order to use password_verify(), you have to have hashed the password using password_hash() This would normally be done when the user first registers or any time the user changes their password
Check the documentation for password_hash() in the PHP manual
I read on stack overflow about flash data only valid till next server request, therefore I made new flashdata for couple of message display..
here below is the my code
This is my controller Controller
public function login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|min_length[5]');
if($this->form_validation->run() == TRUE){
$username= $this->input->post('username');
$password= $this->input->post('password');
$this->load->model('Auth_model');
$user = $this->Auth_model->get_login();
if ($user == 0) {
//echo "<script>alert('wrong username');</script>";
$this->session->set_flashdata("msg","Username does not exists");
redirect("auth/login");
}
else{
print_r($user['username']);
if($username == $user['username'] && $password == $user['password']){
$this->session->set_flashdata("success","You are logged in");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user['username'];
redirect("user/dashboard","refresh");
}
else {
//echo "<script>alert('wrong password');</script>";
$this->session->set_flashdata("msg","Password does not match.");
redirect("auth/login");
}
}
}
$this->load->view('login_v');
}
Model
public function get_login(){
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username' => $username));
$query = $this->db->get();
$user = $query->row();
if ($this->db->affected_rows() != 1) {
return false;
}
else {
$data = array(
'user_id' => $user->user_id,
'username' => $user->username,
'password' => $user->password
);
//print_r($data);
//$this->session->set_userdata($data);
return $data;
}
}
view
<?php if(isset($_SESSION['success'])) {?>
<div class="alert alert-success"><?php echo $_SESSION['success']; ?></div>
<?php } ?>
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php $this->session->flashdata('msg');?>
<form action="" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" id="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" id="password">
</div>
<div>
<button class="btn btn-primary" name="login">Login</button>
</div>
</form>
I want to display
$this->session->set_flashdata("msg","Username does not exists");
but my if else is just doing redirect, the commented script tag works fine though.
How to make "msg" work?
Thanks in advance.
please add echo statement in the view like
<?php echo $this->session->flashdata('msg');?>
OR
<?=$this->session->flashdata('msg')?>
It should be like this :
Get your flashdata by using its key, Should be like this
<?php if(!empty($this->session->flashdata('msg'))) {?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata('msg'); ?>
</div>
<?php } ?>
Or simply do like this:
<div class="alert alert-success"><?php echo $this->session->flashdata('msg'); ?></div>
For more : https://www.codeigniter.com/user_guide/libraries/sessions.html
I am trying to prevent duplicate entries with codeigniter, but it doesn't work anymore.
The data still insert to database despite the same name.
This is the controller code
public function add(){
$title['title']='Add New';
$data['data']='Insert New Group';
$data['exist']= 'This Group already exists';
$this->load->view('add_pbk_g', $data);
}
public function save(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('namegroup', 'Name', 'trim|required|is_unique[pbk_groups.Name]');
if($this->form_validation->run()==false){
$this->add_pbk_g($Name);
} else{
$this->db->insert('pbk_groups',array('Name'=> $this->input->post('namegroup')));
$this->load->model('mpbk_grup');
if($this->mpbk_grup->check_grup_exist('$Name')){
$title['title']='Add New';
$data['data']='Insert New Group';
$data['exist']= 'This Group already exists';
$this->load->view('layout/header', $title);
$this->load->view('add_pbk_g');
$this->load->view('layout/footer');
} else{
$this->mpbk_grup->add;
redirect('cpbk_grup/index');
}
}
}
this is the Model..
function add($data){
return $this->db->create('pbk_groups', $data);
}
function check_grup_exist($namegroup){
$this->db->where('Name', $namegroup);
$this->db->from('pbk_groups');
$query = $this->db->get();
if($query->num_rows() >0){
return $query->result();
} else {
return $query->result();
//return False;
}
}
and this is the view
<form method="post" class="form-horizontal" action="<?php echo site_url('cpbk_grup/save');?>">
<div class="box-body">
<?php echo validation_errors(); ?>
<div class="form-group">
<label class="col-sm-2 control-label">Nama Group</label>
<div class="col-sm-10">
<input type="text" name="namegroup" required="" class="form-control" placeholder="Nama Group">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="submit" value="submit" class="btn btn-info pull-right">Save</button>
Kembali
</div>
<!-- /.box-footer -->
</form>
public function save(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('namegroup', 'Name', 'trim|required|is_unique[pbk_groups.Name]');
if($this->form_validation->run()==false){
$this->add_pbk_g($Name);
} else{
$data = array ('Name' => $this->input->post('namegroup'));
$this->mpbk_grup->check_grup_exist($data);
}
}
Where does $Name on this line come from?
if($this->mpbk_grup->check_grup_exist('$Name')){
Also it should not have quotes around it, should be...
if($this->mpbk_grup->check_grup_exist($Name)){
Try doing this inside save function
Controller Code:
$data = array('Name' => $this->input->post('namegroup'));
$this->Model_Name->check_grup_exist($data);
My Model
Model_Name
$this->main_table = 'pbk_groups';
public function check_grup_exist($data)
{
$query = $this->db->get_where($this->main_table, array('Name' => $data['Name']));
if ($query->num_rows() == 0)
{
$this->db->insert($this->main_table, $data);
return $this->db->insert_id();
}
else
{
return false;
}
Checking duplication data before inserting the data. Let me know if any query occurs.
Once the user login into site unable to fetch the data from database getting blank page if i write foreach condition here is my code.Fetching username and login verification is workig fine.
Controller:
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
}
else{
$this->load->view('welcome');
}
}
Model:
function getprofiledata($id)
{
$this->db->select('profile_details.*');
$this->db->from('profile_details');
$this->db->where(array('profile_details.profile_id'=>$id));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<?php if(isset($records) && is_array($records) && count($records)>0): ?>
<?php foreach($records as $r):?>
<form action="<?php echo base_url();?>profile/updateprofile" role="form" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<?php
echo form_hidden('profile_id',$r->profile_id);
?>
<div class="form-group">
<label class="control-label col-sm-2 " for="name">Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="name" placeholder="Enter name" value="<?php echo $r->first_name;?>" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="profilename">Profile Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="profile_name" placeholder="Enter Profile name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="designation">Designation:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="designation" placeholder="Enter Designation">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
<?php endforeach;endif;?>
You chose the wrong segment number on line $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));.
Take notice that segment counting starts with zero, so segment no 3 is actually the 4th one in the uri.
If you keep the user id inside your session, you should replace $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3)); with $records = $this->profile_model->getprofiledata($this->session->userdata('profile_id'));. And you're done.
add a new session when you login process like bellow in your login model :
<?php
public function login_user($user_name = '', $password=''){
$userdetails = array(
'email' => $user_name,
'password' => md5($password),
'status'=>1,
);
$this->db->where($userdetails);
$query = $this->db->get('profile_details');
if($query->num_rows()):
$user = $query->result();
$sess_arry = array(
'profile_id' => $user[0]->profile_id, // add new session profile_id
'first_name' => $user[0]->first_name
);
$this->session->set_userdata('admin_logged_in', $sess_arry); //add admin details to session
return true;
else:
return false;
endif;
}
?>
And some change your index method like bellow :
<?php
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['country'] = $this->signup_model->getcountry();
$data['states'] = $this->profile_model->getstates();
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id);
$data['records']= $records;
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
$this->load->view('templates/sidebar',$data);
}
else{
$this->load->view('welcome');
}
}
?>
I have added new 3 line because i thinks you are no getting profile id properly in $this->uri->segment(3)
So,
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id);
$data['records']= $records;
I'm using codeigniter for a login form validation. The code was previously working fine, but when I made some modifications, it just do not work now.
When I try to type in wrong or leave blank for password or username, the error message is shown as normal, but when I type in the correct username and password, $this->form_validation->run() just give me FALSE with an empty validation_errors() string.
I've tried to restore my old working controller php, but this error resists.
Full code related is available at
User Controller http://pastebin.com/nt2SDVnv
Login View http://pastebin.com/9hEc0EJB
User Model http://pastebin.com/p1z0zLM8
Only related code are pasted below:
Controller:
<?php
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user_model');
$this->load->helper('url');
$this->load->helper('form');
$this->load->helper('cookie');
}
function login(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'trim|required|md5|callback_password_check');
$this->_username = $this->input->post('username'); //用户名
$remember_me = $this->input->post('remember_me');
$json_string = $this->input->cookie('userinfo');
$userinfo_json = json_decode($json_string);
if(isset($userinfo_json->username)){
if ($this->username_check($userinfo_json->username)){
$this->user_model->login($userinfo);
redirect('admin/dashboard');
}
}
if ($this->form_validation->run() == FALSE){
$this->load->view('account/login');
} else {
$userinfo=$this->user_model->get_by_username($this->_username);
$this->user_model->login($userinfo);
if($remember_me=="on"){$this->user_model->write_session($userinfo);}
redirect('admin/dashboard');
}
}
function username_check($username){
if ($this->user_model->get_by_username($username)){
return TRUE;
}else{
$this->form_validation->set_message('username_check', 'User name not exist.');
return FALSE;
}
}
function password_check($password) {
$password = md5($password);
if ($this->user_model->password_check($this->_username, $password)){
return TRUE;
}else{
$this->form_validation->set_message('password_check', 'Incorrect username or paswsword.');
return FALSE;
}
}
}
View:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - <?=$this->admin_model->get_title();?></title>
<?php $this->load->view('gy/head');?>
</head>
<body>
<?php $this->load->view('gy/header');?>
<div class="hero-unit header">
<div class="container">
<div style="text-align:center;">
<h1>Sign in</h1>
<p class="lead">Log into <?=$this->admin_model->get_title();?>.</p>
</div>
</div>
</div>
<div class="container">
<div class="span5 offset3">
<?php if(validation_errors() !== '' || #(!$err_message == '')){ ?>
<div class="alert alert-error fade in">
×
<strong>Error!</strong> <?=validation_errors('<span>','</span>');?> <?=#$err_message?>
</div>
<?php } ?>
<?php if(#$message!=''){ ?>
<div class="alert fade in alert-success">
×
<strong>Success!</strong> <?=$message?>
</div>
<?php } ?>
<?php echo form_open('login',array('class'=>'form-horizontal')); ?>
<div class="control-group">
<label class="control-label" for="username">User name</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="User name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password">
</div>
</div>
<label for="remember_me" class="checkbox">
<input type="checkbox" id="remember_me" name="remember_me"> Remember me (30 days)
</label>
<div style="text-align:center;">
<input type="submit" name="submit" value="Log in" class="btn btn-primary">
</div>
</Form>
</div>
</div>
<?php $this->load->view('gy/footer');?>
</body>
</html>
Model:
<?php
class user_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library('session');
}
function login($userinfo)
{
$data = array('username'=>$userinfo->username,
'user_id'=>$userinfo->id,
'role'=>$userinfo->role,
'logged_in'=>TRUE);
$this->session->set_userdata($data);
}
function write_session($userinfo)
{
$user_json = json_encode($userinfo);
$cookie = array(
'name' => 'userinfo',
'value' => $user_json,
'expire' => '2592000',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
}
function get_by_username($username)
{
$this->db->where('username', $username);
$query = $this->db->get('users');
if ($query->num_rows() == 1)
{
return $query->row();
}
else
{
return FALSE;
}
}
function password_check($username, $password)
{
if($user = $this->get_by_username($username))
{
return $user->password == $password ? TRUE : FALSE;
}
return FALSE;
}
}
I suspect the trim rule. It doesn't return a Boolean and I suppose you haven't set any error message for that rule. trim() should be run on the username and password, after the validation runs successful. If you just wanna check if the input has blank spaces You could add a rule to check with the strpos() but again in a custom callback. Just remember to use the Identical opperator '===' instead of the equal '==' .
Controller :
$this->form_validation->set_rules('username','Username','callback_space_check|required|xss_clean|callback_username_check');
function space_check($input){
if(strpos(' ',$input)===false){
return TRUE;
}else{
$this->form_validation->set_message('space_check', '%s contains space.');
return FALSE;
}
}