isset() on codeigniter objects - codeigniter

How can I achieve something that looks like:
if (isset($this->session->flashdata('user_profile'))) {}
without:
Fatal error: Call to a member function flashdata() on a non-object in ...
The issue is that it returns an error when that thing isn't set rather than continue as one might expect. If it is set, everything works out fine.
...
I have also tried:
$tmp = $this->session->flashdata('user_profile');
if ($tmp) {
but to no avail.

you don't need isset(); cause CI methods returns false or true
just do
if($this->session->flashdata()){ }
and your error is cause you are surely not loading the session library:
so do this:
$this->load->library('session');
if($this->session->flashdata()){ }
if you prefer (i preferr) you can autoload the session library changing this in your config/autoload.php file:
$autoload['libraries'] = array('session');
so now you don't have to load anytime the session library cause CI autoloads that for you

You can check the existence of $this->session first
if (isset($this->session) && isset($this->session->flashdata('user_profile'))) {
}

For proper validation you must do this method. Weather the values becomes NULL sometimes.
$sessusr=$this->session->userdata('username');
if(isset($sessusr) && trim($sessusr!=''))
{
//to do
}

Have you auto load the session library if not go to config/autoload.php open it and try to add session libarary it will look like this $autoload['libraries'] = array('session'); if you have auto loaded the library than the alternative approach is:
if(!empty($this->session->flashdata('user_profile')): echo $this->session->flashdata('user_profile'); endif;

Related

Always active Session in yii2

I am using yii2-basic. I want to use active sessions everywhere in yii2. How can I do it? I mean where should I put this code (layout.php? web\index.php?) or there is any config in config.php to make session auto active?
$session = Yii::$app->session;
Sorry for my bad english.
In your web.php config file file you could add an event handler:
$config = [
...
'on beforeAction' => function ($event) {
// check Yii::$app->session
},
...
];
There you can set $event->isValid to false what would mean that the action won't get executed. This gets called on any action. See also this.
Or create a component that you load on bootstraping like it is described here.

CodeIgniter sess_destroy does not delete user_data session?

I am creating test case for my CodeIgniter app. However I just found something that I thought should not be happen :
in login.php controller :
public function logout()
{
$this->session->sess_destroy();
redirect('/');
}
So I just created a test to just make sure that session is really destroyed :
public function test_logout()
{
$this->CI = set_controller('login');
// make sure that all session is destroyed
$this->CI->session->set_userdata('test_session', 'some_value');
$this->CI->logout();
// userdata 'test_session' should be removed!
$this->assertTrue(($this->CI->session->userdata('test_session')==null || $this->CI->session->userdata('test_session')==''));
}
However I find that upon running the test case, my test case fails! Upon debug on the last line of test case, I found that the userdata is still exist with value = 'some_value'. I thought that sess_destroy should also delete all the set user data, as per what they described in their website documentation:
This function should be the last one called, and even flash variables will no longer be available. If you only want some items destroyed and not all, use unset_userdata().
I am using Kenji's CIUnit for unit testing.
Is this the correct behaviour or is there something that I missed?
Just found that CIUnit routes the Session to CIU_Session instead of original CodeIgniter's CI_Session. It miss a line that CI_Session does :
$this->userdata = array();
So turns out this is CIUnit's issue instead of CodeIgniter's. Create an issue in their bitbucket page.

Checking for CodeIgniter session_id to not be set

I'm trying to check if its set in my codeigniter application like:
elseif(!isset($this->session->userdata('session_id'))){ ## SESSION data is NOT set
// load a generic 'issue' occurred view.
}
but I keep getting this error, is !isset not valid in Codeigniter? How do I go about easily checking this?
Thanks
You must use the code like below:
$id = $this->session->userdata('session_id');
// your other code
elseif(!isset($id)){
// load a generic 'issue' occurred view.
}
The reason you can see here
You coud also do this ,
elseif($this->session->userdata('session_id') !== false)
{
// SESSION data is NOT set
// load a generic 'issue' occurred view.
}
Note: The function returns FALSE (boolean) if the item you are trying to access does not exist.

codeigniter output cache doesn't work?

I'm using $this->output->cache(n) to cache webpage, but i cannot figure out how does it work.. I didn't find any cache files under system/cache folder...and also after I edit the page and show it again, the content changes, so it seems that the page is not really cached. Can anyone give a help? (i'm using phil's template lib)
my code:
function show(){
$this->output->cache(5);
$this->load->model('page_model');
$var = $this->uri->segment(3, 0); //get About page
$row = $this->page_model->getPage($var);
$this->template->title('about')
->set_layout('default')
->set_partial('styles', 'css')
->set('data', $row->body)
->build('about');
}
THANKS!
Two things, as outlined in the documentation:
Warning: Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for your controller with a view.
Perhaps not using the "native" views is an issue?
Additionally:
Note: Before the cache files can be written you must set the file permissions on your application/cache folder such that it is writable.
Are you sure your application/cache directory has the correct permissions?
Debug this file and check it's actually writing the cache:
system/core/Output.php
// Do we need to write a cache file? Only if the controller does not have its
// own _output() method and we are not dealing with a cache file, which we
// can determine by the existence of the $CI object above
if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
{
$this->_write_cache($output);
}
This works well for me:
function _output($content) {
// Load the base template with output content available as $content
$data['content'] = &$content;
$this->output->cache(600);
$output = $this->load->view('base', $data, true);
$this->output->_write_cache($output);
echo $output;
}
Are you sure your application/cache directory has the correct permissions?
you you to directories application/cache in cpanel , permissions become 777 is OK

Global Variables in CodeIgniter not Working

I want to generate global variables in CodeIgniter by creating my own library and config file. This is what I wrote ini my library file, let's say globalvars.php. I put it in /application/libraries.
class Globalvars{
function __construct($config = array())
{
foreach ($config as $key => $value) {
$data[$key] = $value;
}
$CI =& get_instance();
$CI->load->library('session');
$CI->load->vars($data);
}
}
I want the user id stored in the session to be available in global variable, so I wrote this in my config file. It's named also globalvars.php. It's in /application/config directory.
$config['user']=$this->session->userdata('id');
I then test to see if it's working by write it in my controller this way.
echo $data['user'];
But I get this error in the browser
Message: Undefined property: CI_Loader::$session
Filename: config/globalvars.php
It seems that the session functions is not defined yet. How can I get it work? What have I missed here? Any help would be appreciated.
You cannot use the session library in config file.
The config files are loaded before any libraries, so $this->session is undefined.
The config.php has to be loaded in order for the Session class to even be initialized, as it reads settings from that file.
A lot of issues with this type of thing (setting some "global" data) can be resolved using a base controller, and extending it in your controllers.
// core/MY_Controller.php
MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct(); // Now the Session class should be loaded
// set config items here
}
}
"Normal" controllers will now extend MY_Controller to take advantage of this.
See: http://codeigniter.com/user_guide/general/core_classes.html for more details.
In addition, when you load->vars(), they are available to the view layer only, it does not create a global variable called $data as you seem to be trying to access. If you do this:
$this->load->vars(array('user' => '1'));
You would access it in a file loaded by $this->load->view() like this:
echo $user; // outputs "1"
See: http://codeigniter.com/user_guide/libraries/loader.html
$this->load->vars($array)
This function takes an associative array as input and generates
variables using the PHP extract function. This function produces the
same result as using the second parameter of the $this->load->view()
function above. The reason you might want to use this function
independently is if you would like to set some global variables in the
constructor of your controller and have them become available in any
view file loaded from any function. You can have multiple calls to
this function. The data get cached and merged into one array for
conversion to variables.
I will say that as an experienced Codeigniter user, the concept of a "global vars" class is a bit wonky and probably unnecessary, especially when it's already so easy to get and set config items. You could definitely run into some confusing issues and variable name conflicts with this method (pre-loading lots of view variables on every request).

Resources