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
Related
I want to display an error if a username exists, however no error is being thrown.
the function is on the User.php and im trying to display an error from that function.
i referenced this, however it is not relevant to the OOP way.
User.php
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$row['user_name'] == $username;
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Index.php
<?php
session_start();
require_once 'User.php';
$guest = new User();
if($guest->is_logged())
{
$guest->redirect('profile');
}
if (isset($_POST['btn_signup']) ){
$username = htmlentities($_POST['txt_username']);
$unpass = htmlentities($_POST['txt_password']);
$password = password_hash($unpass, PASSWORD_BCRYPT, ['cost' => 12] );
$unemail = $_POST['txt_email'];
$email = filter_var($unemail, FILTER_VALIDATE_EMAIL);
$guest = new User();
if($email == ""){
$errors[]= "Enter a Email";
}
if($username == ""){
$errors[]= "Enter a Username please";
}
if($password == ""){
$errors[]= "Enter a Password";
}
if($guest->check_user_exists($username)){
$errors[]= "Username Already Taken";
}
if($guest->signup($email,$password,$username)){
$guest->redirect('profile');
die('didnt redirect');
}
else{
$errors[]= "Invalid Entry";
}
}
$title = "Home";
require_once 'layouts/header.php';
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<?php
if(isset($errors))
{
foreach($errors as $error)
{
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
}
else if(isset($_GET['joined']))
{
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered <a href='index.php'>login</a> here
</div>
<?php
}
?>
<h1>Sign Up</h1>
<form action ="" method="POST">
<div class="form-group">
<label for="Email">Email address</label>
<input type="email" class="form-control" aria-describedby="emailHelp" name="txt_email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" aria-describedby="emailHelp" name="txt_username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" aria-describedby="emailHelp" name="txt_password" placeholder="Enter password">
</div>
<button type="submit" name="btn_signup" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
return $stmt->fetchColumn() > 0; // fetchColumn return the number of rows selected
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Your function doesn't actually return or do anything. Return the result of fetch(), if it returns true - a result was found. If it returns false, there was no row matching the username. You don't need to check anything after that, as the fetch() method will only be true if a result was found.
Adjusted for that, your function would look like this
public function check_user_exists($username) {
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username' => $username));
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOExeception $e) {
echo $e->getMessage();
}
}
Also, its not a good idea to output errors directly (on a testing/development environment its fine, but on a live environment you should log it (error_log()) instead.
http://php.net/manual/en/pdostatement.fetch.php
public function ifUserAlreadyExist(string $email):bool{
$sql = "SELECT 1 FROM users WHERE email= :Email";
$statment = $this->conn->prepare($sql);
if (false === $statment) {
return false;
}
$statment->execute([':Email' => $email]);
return (bool)$statment->fetchColumn();
}
//You need to just select 1 object if is already exist and in this case function hint will be so handy, can set the function to boolean and see if it return true or false.
I hope I could help.
I am following the tutorial in this page http://www.kodingmadesimple.com/2016/06/codeigniter-login-and-registration-tutorial-source-code.html and me and other people had found the same error.
It appers to be something wrong in the login controller because it always shows the "Wrong Email-ID or Password!" message, even when the credentials are fine, but I can not find the mistake (although I had found and solved some others), please help me.
controller:
<?php
class login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('user_model');
}
public function index()
{
// get form input
$email = $this->input->post("email");
$password = $this->input->post("password");
//(This was added later for me, as it was needed)
$this->load->helper('security');
// form validation
$this->form_validation->set_rules("email", "Email-ID", "trim|required|xss_clean");
$this->form_validation->set_rules("password", "Password", "trim|required|xss_clean");
if ($this->form_validation->run() == FALSE)
{
// validation fail
$this->load->view('login_view');
}
else
{
// check for user credentials
$uresult = $this->user_model->get_user($email, $password);
if (count($uresult) > 0)
{
// set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->fname, 'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
redirect("profile/index");
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Wrong Email-ID or Password!</div>');
redirect('login/index');
}
}
}
}
related part in the view:
<?php $attributes = array("name" => "loginform");
echo form_open("login/index", $attributes);?>
<legend>Login</legend>
<div class="form-group">
<label for="name">Email-ID</label>
<input class="form-control" name="email" placeholder="Enter Email-ID" type="text" value="<?php echo set_value('email'); ?>" />
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="form-group">
<label for="name">Password</label>
<input class="form-control" name="password" placeholder="Password" type="password" value="<?php echo set_value('password'); ?>" />
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<div class="form-group">
<button name="submit" type="submit" class="btn btn-info">Login</button>
<button name="cancel" type="reset" class="btn btn-info">Cancel</button>
</div>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
If i did not explained myself clearly, or if you need to see more code, you can check it directly on the tutorial link.
Your help will be much appreciated, thanks.
EDIT:
This is the function in the model:
function get_user($email, $pwd)
{
$this->db->where('email', $email);
$this->db->where('password', md5($pwd));
$query = $this->db->get('user');
return $query->result();
}
I had already change "pwd" for "password" and removed the md5 as I dont need it,and now its working.
The form is validating OK as you are getting to this line:
$uresult = $this->user_model->get_user($email, $password);
if (count($uresult) > 0)
Check your get_user function to make sure you are returning the result set, ie:
$this->db->where('user_email', $user_email);
$result = $this->db->get('users');
return $result->result();
Diferent user page for multiple user level.
Where should i put this code to redirect to different pages for each user level.
And maybe I have some errors. How should it be?
$_SESSION['role'] = $row['role'];
if ($_SESSION['role'] == "normalUser")
{
//do stuff here for users
header('Location: memberpage.php');
}
else if ($_SESSION['role'] == "profesor" )
{
//do extra stuff here for only profesor
header('Location: profesori.php');
} else {
header('Location: admin.php');
This is user.php
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT * FROM members WHERE username = :username AND active="Yes" ');
$stmt->execute(array('username' => $username));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['Fname'] = $row['Fname'];
$_SESSION['Lname'] = $row['Lname'];
$_SESSION['indeks'] = $row['indeks'];
$_SESSION['module'] = $row['module'];
$_SESSION['semester'] = $row['semester'];
$_SESSION['email'] = $row['email'];
$_SESSION['titula'] = $row['titula'];
$_SESSION['kabinet'] = $row['kabinet'];
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
return true;
}
}
}
?>
This is login.php
<?php
session_start();
require_once('includes/config.php');
if( $user->is_logged_in() ){ header('Location: index.php');exit; }
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($row = $user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: memberpage.php');
exit;
} else {
$error[] = 'Погрешно корисничко име или лозинка, или вашиот акаунт не е активиран.';
}
}
$title = 'Најави се';
require('layout/header.php');
?>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Ве молиме најавете се!</h2>
<p><a href='./'>Врати се на почетна!</a></p>
<hr>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Вашиот акаунт е активиран, можете да се најавите.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Проверете го вашето сандаче за линкот за промена на лозинка.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Лозинката е променета, можете да се најавите.</h2>";
break;
}
}
?>
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Корисничко име" value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg" placeholder="Лозинка" tabindex="3">
</div>
<div class="row">
<div class="col-xs-9 col-sm-9 col-md-9">
<a href='reset.php'>Ја заборавивте лозинката?</a>
</div>
</div>
<hr>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Најави се" class="btn btn-primary btn-block btn-lg" tabindex="5"></div>
</div>
</form>
</div>
</div>
</div>
<?php
require('layout/footer.php');
?>
Firstly I would recomend to you change attitude about roles admin / professor and everything else should be student (it's more secure, because in your case, if you forget to add role, user will be admin by default).
My second recomendation is you should validate if the user in the session is really user object and not only loggedin value. This validation shoud also be in the User class.
And login.php file code looks wrong. You have to use the User class and you should make login, session values management and checking roles exclusively through this object.
And finally your question - redirecting to specific page should be within login form processing.
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.
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;
}
}