Codeigniter 3 authentication app: loggedin state does not persist across pages - php

I am working on a Codeigniter 3 authentication application. I am new to CI, so the problems are run into are "rookie" level.
The newest one is: if a user has signed in, even though he/she is redirected to the members area, the signed in state does not persist. Navigating to the home page (or on any another page) signs the user out.
Once the user is logged in, I don't want the login form page to be accessible.
The sessions library is globally loaded.
The user model is:
class Usermodel extends CI_Model {
public function user_login($email, $password)
{
$query = $this->db->get_where('users', array('email' => $email, 'password' => $password));
return $query->row();
}
}
The controller looks like this:
class Signin extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('signin');
}
public function signin()
{
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
if ($this->form_validation->run())
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->model('Usermodel');
$current_user = $this->Usermodel->user_login($email, $password);
if ($current_user) {
$current_user_id = $this->session->userdata('user_id', $current_user->id);
$current_user_email = $this->session->userdata('email', $current_user->email);
redirect('home');
} else {
$this->session->set_flashdata("signin_failure", "Incorrect email or password");
$this->load->view('signin');
}
}
else
{
$this->load->view('signin');
}
}
}
The login form view:
<?php echo form_open('Signin/signin'); ?>
<div class="form-group <?php if(form_error('email')) echo 'has-error';?>">
<?php echo form_input(array(
'name' => 'email',
'id' => 'email',
'class' => 'form-control',
'autocomplete' => 'off',
'placeholder' => 'Email address'
));
if(form_error('email')) echo '<span class="glyphicon glyphicon-remove"></span>';
echo form_error('email'); ?>
</div>
<div class="form-group <?php if(form_error('password')) echo 'has-error';?>">
<?php echo form_password(array(
'name' => 'password',
'id' => 'password',
'class' => 'form-control',
'autocomplete' => 'off',
'placeholder' => 'Password'
));
if(form_error('password')) echo '<span class="glyphicon glyphicon-remove"></span>';
echo form_error('password'); ?>
</div>
<div class="form-group">
<?php echo form_submit(array(
'name' => 'login',
'value' => 'Login',
'class' => 'btn btn-success btn-block'
)); ?>
</div>
<?php echo form_close(); ?>
Why is the loggedin state not kept? Thank you!
UPDATE
User Helper:
function is_logged_in() {
$CI =& get_instance();
$user = $CI->session->userdata('user_data');
return isset($user);
}
The navigation bar code:
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<?php if(is_logged_in()) : ?>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><span class="glyphicon glyphicon-user"></span> Hello, user
<span class="caret"></span></a>
</a>
<ul class="dropdown-menu">
<li>My contacts</li>
<li>All contacts</li>
<li>Signout</li>
</ul>
</li>
<?php else: ?>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
<li><span class="glyphicon glyphicon-user"></span> Register</li>
<?php endif;?>
</ul>
</div>

Just after validating whether username and password matches, you have to set data in session, for that you need, small correction:
// if found in table, then save it session
// so that it can be accessible from elsewhere
if ($current_user) {
$this->session->set_userdata(
array(
'user_id' => $current_user->id
'email'=> $current_user->email
)
);
}
To check whether user logged in or not in all other controller, best way is to create helper, and call helper function to validate logged in user.
So for that in helpers directory, say you create file user_helper.php, with below code
<?php defined('BASEPATH') OR exit('No direct script access allowed');
function is_logged_in() {
$CI =& get_instance();
$user = $CI->session->userdata('user_data');
return isset($user);
}
Open file config/autoload.php and add your helper so that in all other controller you can it easily:
$autoload['helper'] = array('user');
So in any controller you can easily check whether user logged in or not like below
if(is_logged_in()){
// proceed authenticated
}else{
// redirect to signin page or somewhere else as per your wish
redirect('signin');
}
You said :
Once the user is logged in, I don't want the login form page to be
accessible.
So you need
public function signin()
{
if(is_logged_in()){
$this->session->set_flashdata('message_name', 'You already logged In');
//redirect to some function
redirect("controller/function_name");
}
// if not logged in then display form
// your other code goes here..
}
and in your view file where you redirect
echo $this->session->flashdata('message_name');

You Need to set userdata first.
change
$current_user_id = $this->session->userdata('user_id', $current_user->id);
$current_user_email = $this->session->userdata('email', $current_user->email);
to
$current_user_id = $this->session->set_userdata('user_id', $current_user->id);
$current_user_email = $this->session->set_userdata('email', $current_user->email);

Related

Can't take and show data name from session login in CodeIgniter

So i wanna make some login page and then show the user name in the dashboard after login succeed. But the name won't show in the dashboard. its just blanks.
there's no error notification or something.
please help. thanks
I'm running on PHP 7
Auth.php Controller
public function index()
{
$this->form_validation->set_rules('email','email',
'trim|required|valid_email');
$this->form_validation->set_rules('password','Password','trim|required');
if($this->form_validation->run() == false){
$data['title']='Login Page';
$this->load->view('templates/auth_header', $data);
$this->load->view('auth/login');
$this->load->view('templates/auth_footer');
}
else{
//success validation
$this->_login();
}
}
private function _login()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$user = $this->db->get_where('user',['email' => $email])->row_array();
if($user){
//user active
if($user['is_active']==1){
//check password
if(password_verify($password, $user['password'])){
//if pass were right
$data = [
'email' => $user['email'],
'role_id' => $user['role_id']
];
$this->session->set_userdata('$data');
redirect('user');
}
else{
$this->session->set_flashdata('message','<div class="alert alert-danger" role="alert"> Wrong password</div>');
redirect('auth');
}
}
else{
//
$this->session->set_flashdata('message','<div class="alert alert-danger" role="alert">
Email has not been activated</div>');
redirect('auth');
}
}
else{
//no email in database
$this->session->set_flashdata('message','<div class="alert alert-danger" role="alert">
Email is not registered</div>');
redirect('auth');
}
}
User.php in controller (control for user)
public function index()
{
$data['user'] = $this->db->get_where('user',['email' => $this->session->userdata('email')])->row_array();
$data['title']='Dashboard - SmartStock';
$this->load->view('user/index', $data);
}
and command for showing the data in page
index.php
<div class="navbar-menu-wrapper d-flex align-items-stretch">
<ul class="navbar-nav navbar-nav-right">
<li class="nav-item nav-profile dropdown">
<a class="nav-link dropdown-toggle" id="profileDropdown" href="#" data-toggle="dropdown" aria-expanded="false">
<div class="nav-profile-img">
<img src="<?= base_url('assets/'); ?>images/profile/default.png" alt="image">
<span class="availability-status online"></span>
</div>
<div class="nav-profile-text">
<p class="mb-1 text-black"><?= $user['name']; ?></p>
</div>
</a>
Perhaps your mistake is Here in Auth->_login() line set_userdata,
replace
$this->session->set_userdata('$data');
with
$this->session->set_userdata($data);

how to call controllers from the cakephp default layout?

I have a controller called UsersController, is there a way I can output some values from this controller to the cakephp default layout?
Here is what I have tried, the default.ctp:
<?php foreach ($users as $user): ?>
<ul class="nav navbar-nav navbar-right">
<?php if (!$this->Session->read('Auth.User.id')) : ?>
<li>
<?php echo $this->Html->link('Login',array('controller' => 'us 'action' => 'login', 'full_base' =>'true)); ?></li>
<li>
<?php echo $this->Html->link('Register', array('controller' => 'users', 'action' => 'add', 'full_base' => true)); ?>
</li>
<?php else: ?>
<li class="dropdown">
<a href="<?php echo $this->Html->url(array('controller' => 'users', 'action' => 'edit', 'full_base' => true)); ?>" class="dropdown-toggle" data-toggle="dropdown">
<?php if(empty($user[ 'User'][ 'filename'])){ ?>
<i class="fa fa-user fa-lg"></i>
<?php }else{ echo $this->Html->image($user['User']['filename'], array('alt' => $user['User']['username'],'class'=>'img-responsive img-rounded','width'=>'32','height'=>'32','style'=>'display:inline; background:red;')); } ?>
<?php $users[ 'User'][ 'username']; ?> <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<i class="fa fa-gear fa-lg"></i> Settings
</li>
<li>
<i class="fa fa-power-off fa-lg"></i> Logout
</li>
<li>Something else here
</li>
<li class="divider"></li>
<li>Separated link
</li>
</ul>
</li>
<?php endif; ?>
</ul>
<?php endforeach; ?>
And here is my AppController.php:
public function beforeFilter(){
return $this->getuser();
}
public function getuser($id = null){
$this->loadModel('User');
$user = $this->User->find('all', array(
'conditions' => array('User.id' => $id)
));
$this->set('users',$user);
}
The problem with this code is that,it keeps returning the following notice,
Notice (8): Undefined index: User [APP\View\Layouts\default.ctp, line
71]
please how do i resolve this issue?
If you want all fields from logged user, you can use this in your view.
$user = $this->Session->read('Auth.User'));
This will return all storage data from users ( username, filename, all fields from user table)
Just change in your controller you have used
public function getuser($id = null){
insted of this use
public function beforeRender($id = null) {
Your AppController.php code should look like this
public function beforeFilter(){
return $this->getuser();
}
public function beforeRender($id = null){
$this->loadModel('User');
$user = $this->User->find('all', array(
'conditions' => array('User.id' => $id)
));
$this->set('users',$user);
}

Client side validation in not working

I am working client side validation in yii2 but it is not working for me.
View File
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\captcha\Captcha;
?>
<ul class="breadcrumb">
<li>Home</li>
<li>Pages</li>
<li class="active">Login</li>
</ul>
<!-- BEGIN SIDEBAR & CONTENT -->
<div class="row margin-bottom-40">
<!-- BEGIN SIDEBAR -->
<!--<div class="sidebar col-md-3 col-sm-3">
<ul class="list-group margin-bottom-25 sidebar-menu">
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Register</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Restore Password</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> My account</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Address book</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Wish list</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Returns</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Newsletter</li>
</ul>
</div>-->
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="col-md-9 col-sm-9">
<h1>Login</h1>
<div class="content-form-page">
<div class="row">
<div class="col-md-7 col-sm-7">
<?php $form = ActiveForm::begin(['id' => 'login-form','class' => 'form-horizontal form-without-legend']); ?>
<?php echo $form->errorSummary($model); ?>
<div class="form-group">
<label for="email" class="col-lg-4 control-label">Email <span class="require">*</span></label>
<div class="col-lg-8">
<?= $form->field($model, 'username',['template' => "{input}"])->textInput(array('placeholder' => 'Username','class'=>'form-control validate[required]')); ?>
</div>
</div>
<div class="form-group">
<label for="password" class="col-lg-4 control-label">Password <span class="require">*</span></label>
<div class="col-lg-8">
<?= $form->field($model, 'password',['template' => "{input}"])->passwordInput(array('class'=>'form-control validate[required]','placeholder'=>'Password')); ?>
<!--<input type="text" class="form-control" id="password">-->
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0">
Forget Password?
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-20">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
<!--<button type="submit" class="btn btn-primary">Login</button>-->
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-10 padding-right-30">
<hr>
<div class="login-socio">
<p class="text-muted">or login using:</p>
<ul class="social-icons">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
<!--</form>-->
</div>
<!--<div class="col-md-4 col-sm-4 pull-right">
<div class="form-info">
<h2><em>Important</em> Information</h2>
<p>Duis autem vel eum iriure at dolor vulputate velit esse vel molestie at dolore.</p>
<button type="button" class="btn btn-default">More details</button>
</div>
</div>-->
</div>
</div>
</div>
<!-- END CONTENT -->
</div>
<!-- END SIDEBAR & CONTENT -->
Colntroller File
<?php
namespace frontend\controllers;
use frontend\models\Users;
use backend\models\SmsData;
use backend\models\SmsDataSearch;
use Yii;
use frontend\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\ArrayDataProvider;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login','index', 'error','register'],
'allow' => true,
],
[
'actions' => ['logout','report','create','delete'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
// 'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionRegister()
{
$model = new Users();
if($model->load(Yii::$app->request->post()))
{
$model->status='0';
$model->is_delete='0';
$model->created_by='1';
$model->password=md5($_POST['Users']['password']);
$model->created_date=date('Y-m-d h:i:s');
$model->role_type='1';
$model->save();
Yii::$app->session->setFlash('success', 'You Have Successfully Register');
return $this->redirect(array('login'));
}
return $this->render('register',['model'=>$model]);
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$data=Yii::$app->db->createCommand("select * from `users` where user_id = '".Yii::$app->user->getId()."'")->queryAll();
if($data[0]['role_type'] == '1')
{
Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
return $this->redirect(array('report'));
}
elseif($data[0]['role_type'] =='0')
{
Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
$url=Yii::$app->urlManager->createUrl('users/index');
return $this->redirect($url);
}
} else {
return $this->render('login',[
'model' => $model,
]);
}
}
public function actionReport()
{
$model= new SmsData();
if($model->load(Yii::$app->request->post()))
{
$fromdate=date('Y-m-d',strtotime($_POST['SmsData']['fromDate']));
$todate = date('Y-m-d',strtotime($_POST['SmsData']['toDate']));
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' AND date(s.created_date) >= '".$fromdate."' AND date(s.created_date) <= '".$todate."'";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
$model->fromDate=$_POST['SmsData']['fromDate'];
$model->toDate=$_POST['SmsData']['toDate'];
return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
}
else
{
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' ";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
}
}
public function actionCreate()
{
$model = new SmsData();
if($model->load(Yii::$app->request->post())) {
$clientID=\frontend\models\Users::findOne(Yii::$app->user->getId());
$model->created_by = Yii::$app->user->getId();
$model->created_date= date('Y-m-d',strtotime($_POST['SmsData']['created_date']));
$model->rating = $_POST['SmsData']['rating'];
$model->text = $_POST['SmsData']['text'];
$model->message_id = 9999;
$model->client_id = $clientID->unique_id;
$model->save();
Yii::$app->session->setFlash('success', 'Data Inserted Successfully');
return $this->redirect(array('create'));
} else {
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND message_id = 9999
AND s.is_delete = 0 AND s.status = 1";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('create',['model'=>$model,'dataProvider'=>$provider]);
}
}
public function actionDelete($id) {
$model = new SmsData();
$command = Yii::$app->db->createCommand('UPDATE sms_data SET is_delete = 1 WHERE sms_id='.$id);
$command->execute();
Yii::$app->session->setFlash('success', 'Deleted Successfully ');
return $this->redirect(array('create'));
}
public function actionLogout()
{
Yii::$app->user->logout();
Yii::$app->session->setFlash('success', 'You Have Successfully Logout');
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->getSession()->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
}
Model :
<?php
namespace frontend\models;
use frontend\models\Users;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
private $_id = false;
private $_name;
/**
* #inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError('password', 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = Users::findByUsername($this->username);
}
return $this->_user;
}
public function getId()
{
if ($this->_id === false) {
$this->_id = $this->user_id;
}
return $this->_id;
}
}
What i need to do for client side validation ? Server side validation is working for me.
This is not a bug! You have to use ActiveForm::validate() for send errors back the browser as it formats the attributes same as ActiveForm renders
if (Yii::$app->request->isAjax && $model->load($_POST))
{
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}
To enable AJAX validation for the whole form, you have to set the
yii\widgets\ActiveForm::enableAjaxValidation
property to be true and specify id to be a unique form identifier:
$form = ActiveForm::begin([
'id' => 'register-form',
'enableClientValidation' => true,
'options' => [
'validateOnSubmit' => true,
'class' => 'form'
],
])
;

Yii Framework - in a main view I can't add a CActiveForm because it needs a model, when I set the model nothing happens

I put this on my view, and I have to add the <?php $model = new Usuarios; ?> and it works but then actually does not send the info to the database.
I tried on another view (index view) and without this it works: <?php $model = new Usuarios; ?>.
<a class="list-group-item">
<form role="form">
<div class="form">
<?php $model = new Usuarios; ?>
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'usuarios-form',
'action' => $this->createUrl("usuarios/create"),
'enableAjaxValidation' => false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div style="padding:1px;" class="input-group input-group-sm">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user" style="color:white"></span>
</span>
<?php echo $form->textField($model, 'Nombre', array('maxlength' => 128, 'placeholder' => 'Nombre y Apellido')); ?>
<?php echo $form->error($model, 'Nombre'); ?>
</div>
<div class="row buttons" style="padding:4%; color:white ; font-size:1.5vmax; font-family: Signika; border-radius:30px">
<center>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Enviar' : 'Save'); ?>
</center>
</div>
<?php $this->endWidget(); ?>
</div>
</form>
</a>
This is what your controller action should look like:
public function actionCreate() {
$model = new Usuarios;
if(isset($_POST['Usuarios'])) {
// Populate the model with values from form
// These attributes must be set to safe in the model rules() function
$model->attributes = $_POST['Usuarios'];
// ->save() will validate the model with the validation rules
// in the Usuarios.php model. If you do not want validation, use ->update()
if($model->save()) {
$this->redirect(array('view', 'id' => $model->primaryKey));
}
}
$this->render('create', array(
'model' => $model, // You pass the model to the view page
));
}
In your model, you need to update the rules() function to accept the fields for saving in the database:
public function rules() {
return array(
array('Nombre', 'safe'),
);
}

CodeIgniter login session not destroying

I'm having a problem in my login session.
This is what I've tried so far:
User.php controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function index()
{
//if(($this->session->userdata('logged_in') == TRUE))
if(($this->session->userdata('username') != "" ))
{
$this->welcome();
}
else {
$data['title']= 'Home';
$this->load->view('include/header',$data);
$this->load->view("frontpage", $data);
$this->load->view('include/footer',$data);
}
}
public function welcome()
{
$data['title']= 'Welcome';
$this->load->view('include/header',$data);
$this->load->view('include/navbar',$data);
$this->load->view('welcome_view', $data);
$this->load->view('include/sidebar',$data);
$this->load->view('include/footer',$data);
}
public function login()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
//md5($this->input->post('password'));
//$this->input->post('password');
$result = $this->user_model->login($username, $password);
if($result)
$this->welcome();
else
$this->index();
}
public function thank()
{
$data['title']= 'Thank';
$this->load->view('include/header',$data);
$this->load->view('thank_view.php', $data);
$this->load->view('include/footer',$data);
}
public function registration()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$this->user_model->add_user();
$this->thank();
}
}
public function logout()
{
$newdata = array(
//'user_id' =>'',
'username' =>'',
'logged_in' => FALSE
);
$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
$this->index();
}
}
?>
User_model.php model
<?php
class User_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
function login($username, $password)
{
$this->db->where("username", $username);
$this->db->where("password", md5($password));
$query = $this->db->get("users");
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
//'user_id' => $rows->id,
'username' => $rows->username,
'logged_in' => TRUE
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
public function add_user()
{
$data=array(
'username'=> $this->input->post('username'),
'password'=> $this->input->post('password')// md5($this->input->post('password'))
);
$this->db->insert('users',$data);
}
}
?>
frontpage.php view
<div class="container">
<div class="jumbotron">
<?php
$attributes = array('class' => 'form-signin');
echo form_open(base_url('login'), $attributes); ?>
<h2 class="form-signin-heading">VMS Login System</h2>
<input type="username" name="username" class="form-control" placeholder="Username" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<button class="btn btn-primary" type="submit">Login</button>
<button class="btn btn-primary" type="reset">Cancel</button> <!-- btn btn-lg btn-primary btn-block -->
<?php echo form_close(); ?>
</div>
</div>
welcome_view.php
<div class="container">
<div class="row row-offcanvas row-offcanvas-right">
<div class="col-xs-12 col-sm-9">
<p class="pull-right visible-xs">
<button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas">Toggle Sidebar</button>
</p>
<div class="jumbotron">
<h1>Van Management System</h1>
<p></p>
</div>
<div class="row">
<div class="col-6 col-sm-6 col-lg-4">
<h2>What's New</h2>
<p>Sample Only</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div><!--/span-->
<div class="col-6 col-sm-6 col-lg-4">
<h2>Charts and Graphs</h2>
<p>Check out sample</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div><!--/span-->
<div class="col-6 col-sm-6 col-lg-4">
<h2>Announcements</h2>
<p>Announcements</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div><!--/span-->
</div><!--/row-->
</div><!--/span-->
The problem is, whenever I log out of the system and go back to the login page, I can always go back to the welcome page, my session is not being destroyed. What I want is, when I log in of course I'm in the welcome page. And when I go back to log in page, the system should redirect me to the welcome view and won't allow me to go to log in page if I'm currently logged in. Any ideas? I tried but nothing is happening :( Help is pretty much appreciated.
Update:
This is how I load the welcome page:
public function index()
{
//if(($this->session->userdata('logged_in') == TRUE))
if(($this->session->userdata('username') != "" ))
{
$this->welcome();
}
else {
$data['title']= 'Home';
$this->load->view('include/header',$data);
$this->load->view("frontpage", $data);
$this->load->view('include/footer',$data);
}
}
public function welcome()
{
$data['title']= 'Welcome';
$this->load->view('include/header',$data);
$this->load->view('include/navbar',$data);
$this->load->view('welcome_view', $data);
$this->load->view('include/sidebar',$data);
$this->load->view('include/footer',$data);
}
I guess you try this
public function logout()
{
$newdata = array(
//'user_id' =>'',
'username' =>'',
'logged_in' => ''
);
$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
$this->index();
}
Your index function User.php controller
public function index()
{
if(($this->session->userdata('logged_in') == TRUE))
{
if(($this->session->userdata('username') != "" ))
{
$this->welcome();
}
}
else {
$data['title']= 'Home';
$this->load->view('include/header',$data);
$this->load->view("frontpage", $data);
$this->load->view('include/footer',$data);
}
}
Welcome function
public function welcome()
{
if(($this->session->userdata('logged_in') == TRUE))
{
if(($this->session->userdata('username') != "" ))
{
$data['title']= 'Welcome';
$this->load->view('include/header',$data);
$this->load->view('include/navbar',$data);
$this->load->view('welcome_view', $data);
$this->load->view('include/sidebar',$data);
$this->load->view('include/footer',$data);
}
}
else
{
$this->index();
}
}

Categories