How to read a session with a PHPSESSID - php

I Know A PHPSESSID in the server how can i read a session variable that is set to a PHPSESSID ( i don't want to use $_SESSION because i don't want start session in this thread ) i only want read session data with using PHPSESSID ??
PHP :
<?php
namespace MyApp;
class readSession extends \Thread {
private $sess_id,$data_name;
public function __construct($SESSID,$data_name){
$this->sess_id = $SESSID;
$this->data_name = $data_name;
}
public function run(){
$data = $this->readSession($this->sess_id,$this->data_name);
}
private function readSession($SESSID,$data_name){
session_id($SESSID);
session_start();
$temp = $_SESSION[$data_name];
var_dump($_SESSION);
session_destroy();
return $temp;
}
}
i write this code to read users session's data but it remove the users session data

First of all, reading another user's session data is a horrible idea. If you need to have shared access to that data - don't store it in the session.
Secondly, reading another doing it via session_start() with the same session ID is an even worse idea - that way you are effectively acting as that user. There's no easy/reliable way to read session data without intercepting it, but that's not by accident, it's exactly because you shouldn't do it.
That being said, don't call session_destroy() and the user's data won't be removed ... destroy means destroy. If you're looking for a way to just close a session, that's session_write_close().

Related

Sessions in Yii

Here I go what am doing is I am using
Yii::app()->SESSION['userid']
with no
Yii::app()->session->open();
at login
Yii::app()->session->destroy();
at logout
I wanna know if dont do the open and destroy session is it worthy . Does Yii do it internally.
One more strange thing I dont know whats happening. In the same browser for a session I can login for multiple users .. this should not happen so.Is it that i am not using the open and destroy session methods .
public function actionLogout()
{
Yii::app()->user->logout();
Yii::app()->session->clear();
$this->redirect(Yii::app()->controller->module->returnLogoutUrl);
}
Please let me know how do i figure this out
For creating yii session
Yii::app()->session['userid'] = "value";
You can get value like this
$sleep = Yii::app()->session['userid'];
And unset session like
unset(Yii::app()->session['userid']); # Remove the session
In case of user signs out , you have to remove all the session.
Yii::app()->session->clear();
After this, you need to remove actual data from server
Yii::app()->session->destroy();
Don't clear session, only logout:
Yii::app()->user->logout(false);
In YII, the session is handled by 'CHttpSession' class - http://www.yiiframework.com/doc/api/1.1/CHttpSession
Should you use the method 'open()' Yii::app()->session->open(); depends on your configuration. If in the main.php, you have set the
'session' => array (
'autoStart' => true,
), then the Session will be started automatically by YII itself.
You can refer the source code for the method 'init()' here - https://github.com/yiisoft/yii/blob/1.1.16/framework/web/CHttpSession.php#L83
Regarding your question about using the methods 'close()' or 'destroy()', the method 'close()' only unsets the keys of Session but 'destroy' removes the whole session data
Once you craeted session it will allow you in same browser multiple time, i mean for same url it will allow you to login, you can just do it rename your session variable with different name and check that particuller variable to login with that.
Session is a Web application component that can be accessed via Yii::$app->session.
To start the session, call open(); To complete and send out session data, call close(); To destroy the session, call destroy().
Session can be used like an array to set and get session data. For example,
$session = new Session;
$session->open();
$value1 = $session['name1']; // get session variable 'name1'
$value2 = $session['name2']; // get session variable 'name2'
foreach ($session as $name => $value) // traverse all session variables
$session['name3'] = $value3; // set session variable 'name3'

Object to Cookie in PHP

I am starting my studies in PHP and I'm having problems with an application:
I need to put information of an object in PHP for a cookie and then receive a cookie to object again on another page.
anyone has any solution to this problem?
The information I want to store in cookie is just some information preferably Customer as background color, size of windows.
<?php
class Client {
private $id;
private $pSize;
private $color;
function __construct($id) {
$this->id = $id;
}
public function getPSize() {
return $this->pSize;
}
public function setPSize($pSize) {
$this->pSize = $pSize;
}
public function getColor() {
return $this->color;
}
public function setColor($color) {
$this->color = $color;
}
}
?>
In a page index.php i have:
<?php
include_once 'Client.class.php';
//Test Preference Client
$client = new Client(1);
$client->setColor("#000000");
$client->setPSize(200);
//using Serialize to put to Cookie
$StringClient = serialize($client);
//Store to Cookie
$_COOKIE['PreferenceClient'] = $StringClient;
?>
In a another page i get the inrofmation:
if(isset($_COOKIE['PreferenceClient'])){
// Unsing Unserialize to Object
$objClient = unserialize($_COOKIE['PreferenceClient']);
//Test data:
echo $objClient->getColor();
//Continue with Performing changes to the client if the information exists...
}
I solved the problem. Thanks to everyone who helped.
before i had tried only get the cookie information without serialize
Guys, this is my first post, I apologize if I did something wrong.
I have to make something up for you?
You could store objects in string (like cookie does) via serialize, unserialize.
setcookie ($name, serialize($object)); // set object
$object = unserialize($_COOKIE[$name]); // get object
But remember that using this approach could be dangerous. PHP Object Injection
You could use json instead of serialization to store stdClass, it would be safe enough.
setcookie ($name, json_encode($object)); // set object stdClass
$object = json_decode($_COOKIE[$name]); // get object stdClass
But it's prefer to use session to store your data. You could even store object without calling serialize, unserialize. But __sleep, __wakeup magic still works.
setcookie, $_COOKIE, serialize, magic with serialization.
The answer is: You don't.
Whenever you take data from the client and use it in your code,
you have to implement security that prevents the case when the user changes his client data and injects something unexpected into your server. The client is easily able to fake and change cookie data, and thus to change your object.
Example:
If we serialize the object from Alma Do's answer and store the values in a cookie, the client/user could see our database auth settings from
public function __sleep() {
return array('server', 'username', 'password', 'db');
}
The client now can change his cookie to use a fake server instead of your server, fake your login / user table and pretend to be admin.
I think this is a case of XY Problem, please let us know what exactly is your goal.
This sounds more then a session function. You shouldn't transfer data over a Cookie. In Cookies you only save short information like a session token or a hash or some settings. To transfer and hold data the PHP session function is much better.
http://www.php.net/manual/de/book.session.php
In your session you can serialize some data if you want or save only an array or a value.
session_start(); // on every page
$_SESSION['test'] = "123123";
echo $_SESSION['test'];
to send serialized object you must use a specified thing like time() to bypass SPAM and control the timeOut!
session_start();
setcookie('myobject',serialize("Myvalue"),(time()+(3600*24*30)));
be sure to get stored on the session :
unset($_SESSION['myobject']);
Store your object
$_SESSION['myobject'] = unserialize($_COOKIE['myobject']);
Restore your Obecjt :
$mySeriaLizedObject = $_SESSION['myobject'];

Codeigniter session generates new session on every page

On every page I see that new session is generated with null userdata
On model constructor
$this->config->set_item('sess_table_name', 'xx_sessions');
Because I want to store this session in another table because the other session table is being used for another login activity
Login function
function login($username,$password)
{
$this->db->where('login',$username);
$this->db->where('pass',$password);
$q=$this->db->get('prof');
// print $this->db->last_query();
if($this->db->count_all_results())
{
$arr=$q->row();
// creating the session
$this->session->set_userdata('login',$arr->id);
$this->session->set_userdata('prof',$arr->profile_id);
// print_r( $arr);
}
else
return FALSE;
}
This login function is on a model. After login and generating the session the page redirects to another page, on that page I see the session builds without any problem but when I move to another page the session losses along with the userdata.
I use the following function to check session data
function print_session()
{
print_r( $this->session->all_userdata());
}
Where I'm wrong ? Tank_auth library and ion_auth library works fine .. I had already used the
Put the session library name into the autoloader configuration, in application/config/autoload.php:
$autoload['libraries'] = array('session');
Then it's available automatically in each controller and everywhere in your application and you get your session data from anywhere:
$session_id = $this->session->userdata('session_id');
And if you don't want to auto load session library then you have to initialize the Session class manually in your controller constructor, use the $this->load->library function:
$this->load->library('session');
For details have a look here:http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
Edit /application/config/config.php and set cookie domain variable
$config['cookie_domain'] = ".yourdomain.com";
It will work!
.yourdomain.com makes the cookie available throughout the domain and its sub-domains.
I have met same problem, and i have searched lots of pages.
I figured out that changing sess_cookie_name solves the problem(new sessions generating issue)
$config['sess_cookie_name'] = 'somenewname'

PHP: start session only when necessary

I have my own Session class, which handles session actions. I wanted to make a mechanism, that the session starts only when it is needed - if no session variables are set, system does not create it.
So that's the code (simplified):
class Session
{
public function __construct()
{
}
protected function startSession($onlyIfExists = false)
{
if (session_id() == '')
{
if ($onlyIfExists && !isset($_COOKIE[session_name()]))
return;
#session_start();
}
}
public function setVar($id, $value)
{
$this->startSession();
$_SESSION[$id] = $value;
}
public function getVar($id)
{
$this->startSession(true); //starts session only if the session-id cookie exists (if the session was already started for this user)
if (isset($_SESSION) && array_key_exists($id, $_SESSION))
return $_SESSION[$id];
else return NULL;
}
}
And then I just always have to use this class object to get/set session variables, e.g.:
$session = new Session();
$session->getVar('test'); //does not start session at the first time
$session->setVar('test', 1); //starts session; after refreshing the page the above line does start session (cookie exists) and the value=1 is returned
Is it a good solution? Do you see any potential drawbacks, vulnerabilities? Or maybe it is a standard to start session each time?
Because in my application any session variables are created only after authorization, so I don't need session for 99.999% of users.
Thank you in advance.
Vulnerabilities: none, I guess. Pretty easy code, not much to go wrong.
Drawbacks: except for more code, none, really.
Advantanges: only in very highly used systems with a few authorized users. Really, starting a session is not that big of a deal, compared to things like Database queries and content compiling. Usually, I would not see a need to optimize this. Just start a session every time, or just on the relevant pages (e.g. if you have a few backend pages that do require auth, just start the session there). Except, of course, you deal with thousands of users per second. I measured a simple session_start() to take about 0.1ms.
Improvements: as zerkms suggests below, starting the session if the cookie exists, or the site wants to write to the session would be the easiest and bulletproof way to manage this and not spawn useless sessions.

Can I handover sessions from Laravel to my simple MVC?

I just want to know if I am able to hand over session variables from Laravel to my custom code. What I mean is: I want to handle log-in through Laravel and pass it to my profile section which is not in Laravel. Most of the routes are handled by a .htaccess file. The goal is to just login with Laravel auth and save that to $_SESSION['user'] var and redirect to /profile. Somehow I don't get that. The session name is the same in both, in Laravel's session.php's cookie name and my custom code's constant. Is there any other factor I should consider ?
Okay here's the code:
namespace Services\Session;
class OldSessionAuth
{
protected $auth;
function __construct()
{
$this->auth = \Auth::user();
}
public function setSession()
{
$_SESSION['user'] = $this->auth->toArray();
$_SESSION['auth'] = 'TRUE';
return true;
}
public function destroy()
{
session_destroy();
session_unset();
}
}
So, this is sort of my Session services, which is initialized only if it passes the Auth from the controller, Now I think I don't need to do that. so I skiped it, Basic Stuffs (Auth::Check()) really. So, I'd just do this in my login method.
$old = new Services\Session\OldSessionAuth();
$old->setSession();
return Redirect::to('/');
The home page is controlled by my custom made MVC and I want to grab the session, which in this case I can't. It shows Array(). There is no session manipulation when retrieving the session.
Laravel already has a pretty good session abstraction so I don't think you needed to use session_start(), $_SESSION etc directly. Sharing an session across two applications is a bit tricky. If you are tied to using the cookie approach, then you have to make sure that the session driver in use is the cookie one. You would also need to ensure that the restrictions on the cookie aren't such that your other application isn't being sent them by the user's browser.
By default, PHP will use a file cookie driver. In this case, what you would have to do in your other application is to read the "PHPSESSID" cookie, set the session ID using session_id() to this and only then would you have access to the session data using the $_SESSION variable in the other application.
This is all pretty hacky though. I would recommend that if you need to share sessions that you make use of a database session driver instead. This way, you are able to share arbitrary session data across applications using a standard interface. In this case, you would just read the "laravel_session" cookie instead to be able to look up the session in the database. There would be many hidden pitfalls if you then wanted to also modify this data from the other application as well though.

Categories