Session not storing data - php

I am using Elliot Haughin's twitter oauth library for codeigniter. It can be found here :
https://github.com/elliothaughin/codeigniter-twitter
I have the following code which authenticates a user with twitter and stores session details.
public function login() {
$this->tweet->set_callback(site_url(''));
$this->tweet->login();
$tokens = $this->tweet->get_tokens();
$user = $this->tweet->call('get', 'account/verify_credentials');
$u = $user->screen_name ;
$data = array(
'user' => $u,
'logged_in' => true
);
$this->session->set_userdata($data) ;
}
This is weird but the logged_in variable is saved whereas the user is not. I am not sure where i am going wrong.

have you include SESSION library or autoload it.
Update:
http://codeigniter.com/user_guide/libraries/sessions.html

Related

How to transfer SESSION created in soap server to soap client code?

I've created a non-wsdl soap server with PHP to run functions from all servers I own. There are bunch of problems on this as you can see from my profile but this I hope is solvable. I cannot transfer SESSION data between server and client.
Already used
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
and set session_id manually
session_id ('ID');
session_start ();
but no luck to transfer SESSION data to client.
Is there a way to transfer SESSION data created on soap-server.php to soap-client.php?
Given this soap server
class MyClass
{
public function __construct(){
session_start();
}
public function login( $user )
{
$_SESSION['user'] = $user;
return true;
}
public function getUserName()
{
return isset( $_SESSION['user'] ) ? $_SESSION['user'] : false;
}
}
$server = new SoapServer( null, array( 'uri' => 'http://localhost/scratch/soap.server.php' ) );
$server->setClass('MyClass');
$server->handle();
And this soap client
$url = 'http://localhost/scratch/soap.server.php';
$config = array( 'location' => $url, 'uri' => $url );
// Call the "login" function to set the user name
$firstClient = new SoapClient(null, $config);
$firstClient->login( array( 'MyUserName' ) ); // ONLY CALL LOGIN ONCE
var_dump( $firstClient->getUserName() ); // TRUE
// Track the cookies
$cookies = $firstClient->__getCookies();
// Second Client fails because we didn't set cookies
$secondClient = new SoapClient(null, $config);
var_dump( $secondClient->getUserName() ); // FALSE
// Works because we've set cookies from the first request
$thirdClient = new SoapClient(null, $config );
$thirdClient->__setCookie( 'PHPSESSID', $cookies['PHPSESSID'][0] );
var_dump( $thirdClient->getUserName() ); // TRUE
You can see I am creating three seperate soap clients, the first performs the login, you can see that the subsequent getUserName() work because we're using the same connection context and its re-using the initial cookies internally.
The second client is independent and has no knowledge of the existing session and fails as expected.
the third client injects the cookie from the first client, and is able to track the username through the session and getUserName() is able to resume without the login() function.
Ideally you would automate the injection of the cookie programmatically instead of my "hard coding" for the purpose of this test
So from here, you have to manage the cookies for the soap client yourself.
If you want the session data itself, there is nothing stopping you from creating an exporting function... eg getSessionData in this example
class MyServerClass
{
public function __construct(){
session_start();
}
public function login( $user )
{
$_SESSION['user'] = $user;
$_SESSION['SomeObject'] = new stdClass();
$_SESSION['SomeObject']->foo = 'bar';
return true;
}
public function getSessionData()
{
return $_SESSION;
}
}

Session data not cleared in codeigniter

I have created a simple login in codeigniter, where user enter his/her username and password and if valid then go to some protected page. Protected page has a link called logout. But the problem is after logout if i directly access to protected page it does not redirect to login page.
my protected page contain
<?php
if (!isset($this->session->userdata['loggedin'])) {
redirect("login");
}
?>
Welcome Dear!!
Logout
I have set the session data after successful user credential.
//set the session variables
$sessiondata = array(
'username' => $username,
'loggedin' => TRUE
);
$this->session->set_userdata($sessiondata);
redirect('admin');
In logout method (login is my controller) I have unset the session data like this-
// Removing session data
$sess_array = array(
'username' => '',
'loggedin' => FALSE
);
$this->session->unset_userdata($sess_array);
But after logout when I access directly to admin page(protected) it does not redirect to login page.
After logout I debugged with this on login page, and it shows the already stored session value.
echo $this->session->userdata['username'];
but when i use on logout method it works fine.
$this->session->sess_destroy();
Can anyone tell me why this is happended? Does unset_userdata not working properly or I have done something wrong? Thanks in advanced.
Ok i solve this problem. The problem is codeigniter does not accept array of pairs when unset session data. i.e
I used this code on my application-
// Removing session data
$sess_array = array(
'username' => '',
'loggedin' => FALSE
);
$this->session->unset_userdata($sess_array);
But codeigniter does not support this now. I altered this code with this below code
// Removing session data
$sess_array = array('username','loggedin');
$this->session->unset_userdata($sess_array);
Now it works fine.
Ref- https://www.codeigniter.com/user_guide/libraries/sessions.html
**In previous versions, the unset_userdata() method used to accept an associative array of key => 'dummy value' pairs. This is no longer supported.**
There issue in handling the session in codeigniter
functionality:
$sess_array = $this->session->all_userdata();
foreach ($sess_array as $key => $val) {
if ($key != 'session_id' && $key != 'last_activity' && $key != 'ip_address' && $key != 'user_agent')
$this->session->unset_userdata($key);
}
Above answer Ashis Biswas is fine and you also need to take care that you should check your login session in your controller as in codeigniter you are accessing your controller function instead of view. if you will check and redirect on view page that will not redirect to your login controller even if you have unset session data.

How to validate session with rest api post

I have API login using session, when mobile apps use login feature actually they hit the API. In API login, i made session login so when the user login it give response session. check my code below:
public function user_post()
{
$data = array (
'username' => $this->input->get_post('username'),
'password' => sha1($this->input->get_post('password'))
);
$result = $this->login_m->user_check($data);
if ($result ) {
foreach ($result as $row ) {
$sess_array = array(
'username' => $row->username,
'email' => $row->email
);
$this->session->set_userdata('logged', $sess_array);
$this->response(array('success' => $this->session->userdata('logged') ));
}
} else {
$this->response(array(404 => 'missing parameter'));
}
}
and the response will be like this below:
* {
* "success":
* {
* "username": "johndoe123",
* "email": "myemail#my.com"
* }
* }
my question is, how to get the session to validate API post? example:
i have post API to store new data. i've imagine this way would be good, set the param to catch the session name 'logged' using codeigniter , in session 'logged' is already has email and username, so will use it as condition to check to table is the email and username is in the table.
$this->session->has_userdata('logged')
so the mobile apps need to save the session in their apps to send again as params. and the code would be like this below:
$data = array(
'idcardno' => $this->input->get_post('idcardno'),
'dateofbirth' => $this->input->get_post('dateofbirth')
);
$addnewpolis = $this->modelname->modelmethod($data2);
thank you guys,
CMIIW
You cannot use sessions like you want in your code with external api calls. You may generate a token from the login and return it. Then on next api calls from your mobile, send this token in order to know the user identity.
Why: Is it good to implement REST api using Sessions?
To generate a token:
https://www.google.com/search?q=generate%20token%20php&rct=j
Then return it in your response and save it somewhere in order to retrieve it on next calls.

Understanding the Session Manager and Zend\Authenticate in ZF2

In the login action I'm having the following code:
public function login($sEmail, $sEncryptedPassword, $bIsClear = true)
{
$manager = $this->getServiceLocator()->get('session_manager');
$manager->start();
Container::setDefaultManager($manager);
$this->auth = new AuthenticationService();
$this->auth->setStorage(new Session('FSP'));
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$this->authAdapter = new AuthAdapter(
$dbAdapter,
'fsp_user',
'email',
'password'
);
$this->authAdapter
->setIdentity($sEmail)
->setCredential($sEncryptedPassword);
$authAuthenticate = $this->auth->authenticate($this->authAdapter);
if ($authAuthenticate->isValid()) {
$user = $this->authAdapter->getResultRowObject();
$storage = $this->auth->getStorage();
$storage->write(
array(
'email' => $user->email,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'id' => $user->id
)
);
}
I have two problems with this code:
1) I'm saving the session in the database, and the session SaveHandler is configured in a service manager. I don't know if once I'm using Zend\Authenticate I should use the session manager too. In the documentation is saying that
"Unless specified otherwise, Zend\Authentication\AuthenticationService
uses a storage class named Zend\Authentication\Storage\Session, which,
in turn, uses Zend\Session."
So my first question is: can I configure the sessionHandler using just Zend\Authenticate or do I have to use the session manager?
2)I can't figured out how session storage is working in ZF. After login, the session data is not persisted in the DB. If I'm doing some debugging I get the following data:
$session = new Container("FSP");
//this returns the session data
var_dump($session->getIterator());
//this returns empty
var_dump($this->auth->getStorage());
//this returns null, but I do have a FSP named cookie with an Id, showing in Chrome's developer tool
$cookie = $this->getServiceLocator()->get('request')->getHeaders()->get('cookie');
$sessionId = $cookie->FSP;
var_dump($sessionId);
However, if I'm doing a refresh on the login (the login action is run again) the data from the previous session is wrote in the DB and not the data from the current one.
So the second question is, why the session data is not persisted in the database at login and at what step in the session instantiation process is the cookie with the session ID created?

Cakephp 2.2.4 does not save Auth User Info after using a alternative authenication

I am trying to create an authentication for facebook users. Right now I check to see if a fb user id exist in my database, if it does then it authenicates, if not, then it data mines the users facebook info and creates a user and then authenicates. It works successfully, the problem is, if I use something like $this->Auth->user('id'); the values return back null. I am curious on what I maybe doing wrong. below is my code
public function fb_authenticate($data) {
$this->Auth->fields = array('username' => 'fbid', 'password' => 'fbpassword');
$this->loadModel('User');
$user_record = $this->User->find('first', array(
'conditions' => array('fbid' => $data['user_id'])
));
if(empty($user_record)) {
$fbu = $this->Facebook->getUserInfo($data['user_id']);
$user_record = array(
'User'=>array(
'username'=>$fbu->username,
'fbid'=>$data['user_id'],
'oauth_token'=>$data['oauth_token'],
'access_token'=>$data['access_token'],
'firstname'=>$fbu->first_name,
'lastname'=>$fbu->last_name,
'fbpassword'=>$this->Auth->password($data['user_id']),
'role'=>'user'
));
$this->User->create();
$this->User->save($user_record,null);
}
if (!$this->Auth->login($user_record)) {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
It authenicates and lets the user in, but it does not store the users info in the Auth component session. what could be the problem ??
if I debug debug($this->Auth->user()) I can see the data but if I pull a field individually debug($this->Auth->user('id')); it returns null.
Change $this->Auth->login($user_record)
to $this->Auth->login($user_record['User']).

Categories