SESSION in codeigniter - codeigniter

$session = array('name' =>'chapter');
$this->session->set_userdata($session);
$sess = $this->session->userdata('name');
This is my session & this is not able to go in another method of same class why?

You are doing it wrong. The $session variable is local in which method you declare. You have to load Session if not already in the controller.
Now to set Session:
$this->session->set_userdata('your_variable_name', $session);
to get data:
$sess = $this->session->userdata('your_variable_name');

First, you need to load SESSION library in your controller, use the syntax below:
$this->load->library('session');
then only set_userdata and userdata will work.
To set data for session:-
$session = array(
'name' => 'chapter',
);
$this->session->set_userdata($session);
for retrieving Session Data:-
$this->session->userdata('name');

Related

store post value in session variable

i post value through ajax in codeigniter controller function , and trying to store value in session like this
function abc{
$studio = $_POST['studio'];
$trnr_type = $_POST['trnrtyp'];
$this->session->set_userdata('studio',$studio),$this->session->set_userdata('trnr_type',$trnr_type)
}
and use this value
$st = $this->session->userdata('studio');
$tr = $this->session->userdata('trnr_type');
but not getting value in session variable.
Load the session library in your controller by the following
$this->load->library('session');
then you have to post the data to the codeigniter controller
then at the controller you have to do the following
$sess_array = array(
'studio' => $this->input->post('studio'),
'trnr_type' => $this->input->post('trnrtyp'),
);
$this->session->set_userdata('studio',$sess_array);
//set user data
$this->session->set_userdata('username',$username);
//get user data
if($this->session->has_userdata('username'))
{
$userid = $this->session->userdata('username');
}
Hope this is what u are looking for
Before call abc function load sesion library
function abc() {
$session = array('studio'=>$_POST['studio'],'trnr_type'=>$_POST['trnrtyp']);
$this->session->set_userdata($session);
}
1. Load session library into your controller:
$this->load->library('session');
2. Get your data:
$studio = $this->input->post('studio');
$trnrtyp = $this->input->post('trnrtyp');
3. Set session data:
$this->session->set_userdata('studio', $studio);
$this->session->set_userdata('trnrtyp ', $trnrtyp );
4. Get session data:
$st = $this->session->userdata('studio');
$tr = $this->session->userdata('trnr_type');
This is what the user guide says to do
http://www.codeigniter.com/user_guide/libraries/sessions.html#adding-session-data
public function abc() {
$sessiondata = array(
'studio' => $this->input->post('studio'),
'trnrtyp' => $this->input->post('trnrtyp')
);
$this->session->set_userdata($sessiondata);
}
Make sure you have set your session save path on config.php don't leave it null

How to delete session in cakephp 3.0?

all code is in one controller
My code goes like this.
public function login()
{
$session = $this->request->session();
$session_event_id = $session->read('Events.event_id');
$session_division_id = $session->read('Events.division_id');
if(!$session_event_id || !$session_division_id) {
$event_table = TableRegistry::get('Events');
$event = $event_table->find('all', ['fields' => ['id'], 'order' => 'id desc'])->first();
$session->write('Events.event_id', $event->id);
$session_event_id = $session->read('Events.event_id');
$division_table = TableRegistry::get('Divisions');
$division = $division_table->find('all',['fields' => ['id'], 'conditions' => ['event_id' => $event->id]])->first();
$session->write('Events.division_id', $division->id);
$session_division_id = $session->read('Events.division_id');
}
}
By above code i am able to write and read session values but while logout i want to delete those session data
public function logout()
{
$session = $this->request->session();
$this->$session->delete();
return $this->redirect($this->Auth->logout());
}
Warning (4096): Object of class Cake\Network\Session could not be
converted to string [APP/Controller/UsersController.php, line 56]
Notice (8): Object of class Cake\Network\Session to string conversion
[APP/Controller/UsersController.php, line 56]
Error: Call to a member function delete() on a non-object File
/var/www/html/MEX/src/Controller/UsersController.php
You're looking for $this->request->session()->destroy();
http://book.cakephp.org/3.0/en/development/sessions.html#destroying-the-session
Just a tip - there's not much of a point for storing a variable $session for a function that small, where the reuse of $session isn't necessary. The only case I'd store $this->request->session(); in a variable is when I'm accessing the session for multiple read and writes all in the same function.
(As far as the error is concerned, #Eagle is correct in that you're referencing '$this' twice by the use of that stored variable.)
Thank You for your supports and help finally i found solution of my problem by myself
$session = $this->request->session();
$session->delete('Events.event_id');
$session->delete('Events.division_id');
by doing so, i am able to clear session data. Thank you

Symfony2 functional test with Session and Post

I am trying to write some Symfony2 functional tests, using PHPUnit, that simulate a logged-in user requesting some resource via an AJAX call.
The test first simulates a user logging-in using the standard FOSUserBundle log-in form;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class MyWebTestCase extends WebTestCase {
public function login($username, $password = 'password')
{
$client = static::createClient();
$client->followRedirects(true);
$crawler = $client->request('GET', '/login');
$form = $crawler->selectButton('Login')->form(array(
'_username' => $username,
'_password' => $password,
));
$crawler = $client->submit($form);
return $client;
}
}
Then, the test gets an entity from the database and sets it in a session variable, then sends a POST request to retrieve the requested resource, using some JSON which includes extra information about what is being requested (in the actual application, some JavaScript composes the JSON in response to the user's actions which is then submitted via AJAX);
$this->client = $this->login('user#domain.com', 'password');
// we want element number 6 from the fixtures
$chart = $this->em->getRepository('MyBundle:Element')->find(6);
$guid = $chart->getGuid();
$this->client->getContainer()->get('session')->set($guid, $chart);
$link = sprintf('/viewer/data/%d/%s', 1, $guid);
$crawler = $this->client->request('POST', $link, array(), array(),
array('CONTENT_TYPE' => 'application/json'),
'{"filters":[]}');
When the tests reach this point, an error is generated;
ini_set(): A session is active. You cannot change the session module's ini settings at this time
I'm using Symfony 2.6.5 and PHPUnit 4.5.0
Do you use mock sessions for your test? If not try this.
Config_test.yml
framework:
test: ~
session:
storage_id: session.storage.mock_file
The native session storage is meant to handle a single request per process which may lead to your bug. if its your case.

CodeIgniter: unset all userdata, but not destroy the session

Is there a way to unset ALL userdata in a session without having to use session destroy? I'm trying to log my user out and need to unset all userdata one at a time. It's becoming tedious to keep track of all possible userdata set in session. I just want to unset everything that might have been set in userdata.
This is very simple!
$this->session->unset_userdata('some_name');
or
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
I hope this helps!
Edit: It looks like you actually don't keep track of anything in your session (kind of strange?). You could call this function I wrote up:
function unset_only() {
$user_data = $this->session->all_userdata();
foreach ($user_data as $key => $value) {
if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
$this->session->unset_userdata($key);
}
}
}
Of course, that assumes you use the default CI session setup though.
Copied from codeigniter forum:
All it does is kills the users cookie, but the userdata will
remain within the session class until the end of the current request.
The session will be reinitialised on the next request, and there will
be no userdata available. Basically, all it does is severs the link
between the user and the server session, but the data still remains
until the end of the request.
If it’s that much of an issue, you can do this:
$this->session->userdata = array();
I manage it please try it .
$this->load->library('session');
// write parameter your session data
$this->session->unset_userdata('sessiondata');
// if you want to session unset group then try it
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
You can try this one.
In the latest version above code is not working.
$unset_array_items = array('token_id', 'last_id');
$this->session->unset_userdata($unset_array_items);

How to access DB config in CodeIgniter?

In my application, I need to know what values are assigned to the DB config items such as database, username, etc. How do I access those information?
I don't have enough rep to comment on Matt Browne's correct answer but just adding a bit incase anyone forgets...
load the db driver like so first:
$this->load->database();
then you can easily access what you need:
$this->db->hostname
$this->db->username
$this->db->password
$this->db->database
Pretty much all the config values are accessible via $this->db (take a look at system/database/DB_driver.php).
That's what worked for me...none of the other suggestions here did.
As an example
$config = [
'host' => $this->db->hostname,
'port' => '3306',
'username' => $this->db->username,
'password' => $this->db->password,
'database' => $this->db->database
];
In case you have multiple database connection groups defined in config/database.php, for eg :
$db['dbname']['hostname'] = "localhost";
$db['dbname']['username'] = "root";
$db['dbname']['password'] = "root";
$db['dbname']['database'] = "web_dbname";
$db['dbname_readonly']['hostname'] = "localhost";
$db['dbname_readonly']['username'] = "root";
$db['dbname_readonly']['password'] = "root";
$db['dbname_readonly']['database'] = "web_dbname_readonly";
If you want to use the connection params of any particular db in a controller or model:
$db = $this->load->database('dbname');
If you want to use in a helper or library :
$ci = &get_instance();
$db = $ci->load->database('dbname');
The connection params will be available as $db->hostname, $db->username etc.
I stumbled across this, looking for a way to find all of the DB settings. Was not able to find a solution on-line, but found some useful code in system/database/DB.php
Here's my approach, get the contents of the entire database config:
if ( ! file_exists($f = APPPATH.'config/'.ENVIRONMENT.'/database.php')
&& ! file_exists($f = APPPATH.'config/database.php'))
{
show_error('The configuration file database.php does not exist.');
}
include($f);
// Use a NEW variable.
// Because $db is a reserved name!!
$db_settings = $db;
foreach($db_settings as $key => $value) {
// .. do something with .. $this->database->load($key);
// .. do something with .. $value['database'];
// .. do something with .. $value['password'];
}
You should be able to get at your configuration setting like this :
$this->config['env']
You can retrieve it with this:
http://codeigniter.com/user_guide/libraries/config.html
$this->config->item('item name');

Resources