Flashdata not getting cleared in Codeigniter - php

I am using Codeigniter 2.1.4 and I have facing some issues with flashdata.
When I successfully submit record I can display the flashdata message. But if go to the other page from the page where flashdata message was displayed and then go back to previous page using browser back button it shows me flashdata message again.
How to clear flashdata message once it used?
I think its not the flashdata issue its cache problem. I am confused why this is happening. If its cache issue then how to remove it?
Below is code I have used,
//In the manage of controller
$this->session->set_flashdata('message', "Record updated successfully.");
// In the view of controller
$data['message'] = $this->session->flashdata('message');
// In the view page
echo $message;

Flash disappears only after next refresh

your code in controller is right
//In the manage of controller
$this->session->set_flashdata('message', "Record updated successfully.");
redirect('controller_name/function_name','refresh');
now in view use like this
if($this->session->flashdata('message')){echo $this->session->flashdata('message');}
hope it will work

Go to System->libries->Session->session.php
Find flshdata fuction and replace with this
public function flashdata($key = NULL)
{
if (isset($key))
{
$return= (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) && ! is_int($_SESSION['__ci_vars'][$key]))
? $_SESSION[$key]
: NULL;
unset($_SESSION[$key]);
return $return;
}
$flashdata = array();
if ( ! empty($_SESSION['__ci_vars']))
{
foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
is_int($value) OR $flashdata[$key] = $_SESSION[$key];
}
}
unset($_SESSION[$key]);
return $flashdata;
}

You must redirect the page somewhere after $this->session->set_flash('item','value');
Example:
if ($this->form_validation->run() == FALSE){
$this->session->set_flashdata('error',validation_errors());
redirect(base_url().'user/login');
}
else{
$this->session->set_flashdata('success','Thank you');
redirect(base_url().'user/login');
}
Usually developer make a mistake when they submit data to same page. They set flash data but forget to redirect.

if you want to clear set_flash in controller or another view file, then you can use this simple code.
$this->session->set_flashdata('error', 'User not found...'); //create set_flash
destroy set_flash
//echo "<pre>"; print_r($_SESSION); die; //for check
if(isset($_SESSION['error'])){
unset($_SESSION['error']);
}

$this->session->set_flashdata('message', "Record updated successfully.");
After setting the flashdata redirect to some function or to the same function.

If you refresh in the same controller function the flashdata won't be deleted.Also going back and forth in the browser does't affect the flashdata.
to clear the flashdata redirect to another controller function and it will work.

As Code igniter does not offer the possibility to destroy the flashdata, you can work around this problem with a second fictitious call of the flashdata function without echo :
if ($this->session->flashdata('message')) :
echo $this->session->flashdata('message'); // First normal call
$this->session->flashdata('message'); // Second fictitious call
endif;

Looks like this will be fixed in 3.1.12: https://github.com/bcit-ci/CodeIgniter/pull/6013

It is php version issue. you need to modify your session file.
go to your Session.php file
find the _ci_init_vars function and add this "$value === 'old' ||" in the elseif condition.
or replace the function with following.
protected function _ci_init_vars()
{
if ( ! empty($_SESSION['__ci_vars']))
{
$current_time = time();
foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
if ($value === 'new')
{
$_SESSION['__ci_vars'][$key] = 'old';
}
// Hacky, but 'old' will (implicitly) always be less than time() ;)
// DO NOT move this above the 'new' check!
elseif ($value === 'old' || $value < $current_time)
{
unset($_SESSION[$key], $_SESSION['__ci_vars'][$key]);
}
}
if (empty($_SESSION['__ci_vars']))
{
unset($_SESSION['__ci_vars']);
}
}
$this->userdata =& $_SESSION;
}

I have faced same problem when I have update php version 7 to php 8.
You can manually unset flash data just after display your error or success message.
$this->session->unset_userdata('err_msg')

it's work : https://github.com/bcit-ci/CodeIgniter/pull/6013#issuecomment-1316482414
This is an issue in newer version of php . You can fix it by replacing line 420 in system/libraries/Session/Session.php:
elseif ($value < $current_time)
with
elseif ($value === 'old' || $value < $current_time)
thanks,

Related

Redirect after a DB update

So, I'm using this php function to update a database in a site.
public function ativo($id, $ativo) {
if ($ativo == 0) {
$data['ATIVO'] = 1;
}
if ($ativo == 1) {
$data['ATIVO'] = 0;
}
$this->db->where('CLIENTE.idCLIENTE', $id);
$this->db->update('CLIENTE', $data);
header("Location: -imagine-a-web-address-here");
}
The problem is, I keep getting a blank page after the db update, so the header() isn't really helping me.
Is there any problem with the code or other function to redirect to the address? Thx for the help.
What is the error you got?
Try this;
header('location:'.$_SERVER['HTTP_REFERER']); or redirect($_SERVER['HTTP_REFERER']);

Session flashdata doesn´t work on form submit

I am using the ion-auth "library" for codeigniter (https://github.com/benedmunds/CodeIgniter-Ion-Auth) and I am getting a trouble with the flashdata. This is a sumary of code:
public function reset_password($code = NULL)
{
if (!$code)show_404();
$this->user = $this->ion_auth->forgotten_password_check($code);
if ($this->user)
{
//setting the rules
if ($this->form_validation->run() == false)
{
//more code
$this->_get_csrf_nonce();
/*
One of the things this function (_get_csrf_nonce) makes is:
$this->session->set_flashdata('csrfkey', $key);
$this->session->set_flashdata('csrfvalue', $value);
*/
//The next thing is load the view with the form
}
else //form is running
{
echo "flashdata csrfkeyvalue: ".$this->session->flashdata('csrfvalue')."<br>";
die;
//more code, but not important by the moment
}
}
}
Well, the echo of $this->session->flashdata('csrfvalue') when the form is submited allways show nothing.
If I make something like:
private function _get_csrf_nonce(){
/*$this->load->helper('string');
$key = random_string('alnum', 8);
$value = random_string('alnum', 20);
$this->session->set_flashdata('csrfkey', $key);*/
$this->session->set_flashdata('csrfvalue', $value);
redirect(base_url("auth/test"));
//return array($key => $value);
}
public function test()
{
echo "flashdata csrfkeyvalue: ".$this->session->flashdata('csrfvalue')."<br>";
}
In this case... it works. The view I am using to the form is very very similar from this: https://github.com/benedmunds/CodeIgniter-Ion-Auth/blob/2/views/auth/reset_password.php
Thanks.
SOLUTION
After fighting a little, I was looking for something that could make a new request between the view of form was loaded and the form was submited... finally, I discover (I didn´t remember) a javascript that is request though a controller (to translate some texts, based on this tutorial: http://www.student.kuleuven.be/~r0304874/blog/international-javascript-files-in-codeigniter.html). I was loaded in this way:
<script src="<?=site_url('jsloader/login.js');?>" type="text/javascript"></script>
Thanks.

Prevent duplicate code with checking sessions

I have three session levels:
session->is_logged_external
session->is_logged_admin
session->is_logged_staff
I have a small function bellow (checkLogin) that I call to display a message if they do not have the session needed to accesses the page.
As you can see I have commented out code at a attempt to create a function that checks if the session is in one of these categories if so let them see page if not display message.
public function checkLogin()
{
$logged_admin = $this->session->is_logged_admin;
//$logged_external = $this->session->is_logged_external;
//$logged_staff = $this->session->is_logged_staff;
if(!isset($logged_admin) || $logged_admin != TRUE) {
echo 'Im sorry, you do not have administrator pillages';
echo anchor('main/index', 'Return home');
die();
}
//else if(!isset($logged_external) || $logged_external != TRUE) {
//echo 'Im sorry, you do not have external pillages';
//echo anchor('main/index', 'Return home');
//}
//else if(!isset($logged_staff) || $logged_staff != TRUE) {
//echo 'Im sorry, you do not have staff pillages';
//echo anchor('main/index', 'Return home');
//}
}
This did not work so I commented the code out. My next idea was to create three functions one for each of the sessions and call what functions I need for each page within the controller however, this is basically the same code repeated 3 times but with different session names, Is this the right way of doing this ?
Thanks guys.
example of idea two
First Admin session function
public function checkLoginAdmin()
{
$logged_admin = $this->session->is_logged_admin;
if(!isset($logged_admin) || $logged_admin != TRUE) {
echo 'Im sorry, you do not have administrator pillages';
echo anchor('main/index', 'Return home');
die();
}
}
Second Staff session function
public function checkLoginStaff()
{
$logged_admin = $this->session->is_logged_staff;
if(!isset($logged_staff) || $logged_staff != TRUE) {
echo 'Im sorry, you do not have staff pillages';
echo anchor('main/index', 'Return home');
die();
}
}
and a third that would be external, then I could call each one when I need them, right?

Session in Yii application

I want to learn sessions in Yii, thus I created a simple login form. Also I want to "set" session in this project.
My login action
public function actionLogin()
{
Yii::app()->session['userid'] = "value"; // where i should put line ??
$model=new LoginForm('login');
if(isset($_POST['ajax']) && $_POST['ajax']==='form-reg')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['regist']))
{
$model->username=$_POST['istiad'];
$model->password=$_POST['parol'];
if($model->validate() && $model->login()) {
$this->redirect(array( 'update','id'=>$this->getIdByUsername($model->username ) ));
/* $this->render(
'update',array(
'model'=> $this->loadModelByUsername($model->username ) ) );*/
}
}
else
$this->redirect(Yii::app()->user->returnUrl);
}
logout action
public function actionLogout()
{
Yii::app()->user->logout();
unset(Yii::app()->session['userid']); // also this,
Yii::app()->session->clear(); // this
Yii::app()->session->destroy(); // and this line ??
$this->redirect(Yii::app()->homeUrl);
}
p.s: PLEASE EXPLAIN ME what is the userid in unset(Yii::app()->session['userid']); ? I couldn't understand (because I'm new in Yii). It's just only a variable or any attribute of the db table name?
I copied the lines from this topic.
Thanks. Best regards.
Set session after validation user name and password. Like here..
if($model->validate() && $model->login()) {
Yii::app()->session['userid'] = "value"; //here
$this->redirect(array( 'update','id'=>$this->getIdByUsername($model->username ) ));
}
unset destroys the specified variable.
unset(Yii::app()->session['userid']);
Here userid is session variable. It is destroyed.
Yii::app()->session->clear();
clear() is used to remove all sessions.
After clear(), you need to remove actual data from server using
Yii::app()->session->destroy();

Little Active record views updating

I need little Active record help. I am trying to update page views which i store in database. Each time post() function runs, add +1 . Here is my code:
public function post($id) {
if($id == NULL){
redirect('blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1');
$this->db->update('entry');
Please help!
Correct your code like this for example:
public function post($id) {
if(!isset($id) || (int) $id<=0){
header('Location: /blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1');
$this->db->update('entry');
}
Mark the header('Location: /blog') - you should put here your real server path to the blog.
If you use a custom redirection function, like your redirect() then check if the is an output before calling her. Header redirection only works if no other output is sent to the browser before invoking it.
public function post($id) {
if($id == NULL){
redirect('blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1',FALSE);
$this->db->update('entry');
FALSE turns off Active record escaping,by default it ignores +1.

Categories