Implementing own Session Management in PHP - php

What options are there to implement an own session management in PHP?
Is there a nice way to implement a component which performs all session tasks?
How can i construct a class which receives the HTTP Request and Response during one request process?
I only found the option "session_save_handler" which seems to define the storage handler. What I need is to replace the whole session management.
Is there another way using the PHP configuration or do I have to implement my own controller which receives all requests and calls my session management?
Thanks for your help
Regards Michael

No, I'm sorry to say, there is no interface to switch the built in 'modules' to your own. There are some hooks ( e.g: session_save_handler(), set_error_handler() ), and that's unfortunately it.
The $_SESSION is a 'super global' and should IMO not be set directly either way if you're working on a bigger projects. Then it would be better to use a custom class responsible for handling sessions. Will make the code easier to debug and such on.

I am not sure, what you want to achieve. It seems more like you want to abstract away from the $_SESSION variable than that you want to change the storage.
Take a look at the way the Zend or the Solar framework handle the Session access.
http://www.phpeveryday.com/articles/Zend-Framework-Session-Introduction-P571.html
http://solarphp.org/manual:sessions
How can i construct a class which receives the HTTP Request and Response during one request process?
I don't know, what you mean by receiving the response, but the frameworks have front-/page-controllers which route to the chosen action, then call a method that can access the Session (read/write) and Request (read) objects and generates a Response object which is then rendered through a template.
For automatic testing you can construct your own Request and Session objects and pass them to the page controller.

You said it yourself in one of the comments. Just wrap the $_SESSION in a class. I don't think you can replace it, but you can certainly build your own interface to it.
You could, for example. Build a class that is constructed first thing and call session_start() inside the constructor

Using the session_save_handler() function allows to handle how the session information is stored and retrieved.
By default PHP stores the session information in temporary files located somewhere on your web server. You can define callback functions using the session_save_handler() function where you can have this information stored in a database table instead.
Even if you handle sessions with your own defined functions with the session_save_handler() function you would still access the information with the superglobal variable $_SESSIONS.

Check out this page from the php online manual. Has lots of useful information with regards to your question. Hope it helps.

You could create a session implementation with cookies and a database. You set a cookie on the client's machine. Then, you run a lookup on a database, something like this:
+--------+------+
| sessid | data |
+--------+------+
Where sessid contains a reference to the cookie (probably some king of md5 or SHA hash), and data is something like a JSON or Serialized array.
The functions:
You can use the function runkit_function_redefine(), which is part of the Runkit API, to redefine the session_xxxx functions.
Note: Runkit is part of PECL. That is, NOT BUNDLED WITH PHP. You will have to install it yourself.
The session variable:
$_SESSION = &SessionClass->data;
Simplicity itself: just make $_SESSION as a reference to YOUR data.

Related

Advised way to access PHP class instance in AJAX call?

I have a pretty big PHP class instance with quite a lot of methods and potentially including semi-sensitive data that I would need to be able to access through AJAX. I've read about and successfully tested $_SESSION to transfer the class and object, but there seem to be some security concerns. Eg. see How safe are PHP session variables?, and PHP Session Hijacking.
Previously I 'solved' this by simply require'ing the class and re-instantiating the object on every AJAX call/ or making those methods I needed static (after checking for a token and a constant), but I feel like this should be quite performance-heavy (how long does it take for PHP to initialize an object which reads in 200+ JSON/XML files?).
Another option I see is serializing the data in a temp file, but really I have no idea nor experience of what is the best way to go from a performance vs security point of view... Any help will be appreciated, thanks.

PHP Storing a Class in session

I have searched and searched and found tons of examples but it seems that everyone has a different opinion about how and when to use session, some use it some say it is evil...
Here is my use case.
I have a Class that has several variables that will need to be used on every page in my application. These variables values are set by making a SOAP call to an API that I am working with. The SOAP call is relatively quick but I am trying to understand how to avoid making a call to the API on every page. I would much prefer to make the call once and then "store" the values somewhere.
I would think that I would just create an Instance of my class on some say Init.php page, make the SOAP calls and then store the whole class in session. Then on all of my pages include the Init.php page. In that page I would do a check to see if the Class existed in the session and if so then pull it form the session.
I know I have to serialize\deserialize the class to do this but I am looking for some feedback here on weather this is the right way to satisfy this use case or if there is a better option?
I am kinda new to PHP, mostly a .NET guys and in .NET the session is generally the best way forward.
All input is appreciated.
thanks
I assume when you stay "serialize\deserialize the class," you really mean you want to serialize/deserialize a class instance (an object) in the session, not the actual class definition. Be careful when using the terms class, instance, and object, since they are not interchangeable and can lead to confusion.
An object can be easily stored in a PHP session. PHP automatically serializes the object at the end of the request and deserializes it when the session data is read on the next request.
session_start();
if (!isset($_SESSION['soap'])) {
$_SESSION['soap'] = doSoapRequest(); // Returns an instance of your class.
}
When an object is serialized, only the variables defined in the class are saved along with the name of the class. When it is unserialized, the class definition must be available (that is, either autoloader or explicitly included into the script). Unserializing will create a class instance with the same data as the object that was previously serialized.

How to manage the session start in CakePHP when building a REST API?

I have read this post earlier:
Generally splitting admin and web app into two entities
Basically the gist of it is that we can combine the api side of things and the web front side of things together in one cakephp app. However, as you know REST is stateless and there is no reason to expect the client to keep a cookie or anything like that. Do you guys know when exactly does the session_start function gets trigger in CakePHP? I really want to avoid the running session_start when my API end points are hit. However, I will need session to start when my regular web fronts are hit.
For cake v2+, in general do not do any of the following:
make calls to CakeSession
Load session component or use session helper
remove $this->session->flash() from layouts
dont use auth component
If you are still getting sessions started (can tell by getting a cookie in the response header), its easy to track down who is starting the session. Just add the following lines to lib/Cake/Model/Datasource/CakeSession.php in the start() method:
public static function start() {
debug_print_backtrace();
exit();
...
}
Make a request and you'll see a call stack of who the culprit was :)
session_start() gets triggered in CORE\Cake\Model\Datasource\CakeSession.php. if you do not want to trigger the session_start(), be sure to not include the session component or helper in your controller. Also, be sure not to call session or use Auth component, as it also can automagically trigger session_start() in some cases.

Perl's CGI::Session doesn't seem to find existing session (from PHP)

I'm trying to instantiate a CGI::Session object from a session created in a separate PHP script; however, when I Dumper() the object, I see that the _CLAIMED_ID session id (which matches the PHP's session_id()) is different from the _SESS_ID (or whatever) stored in the _DATA member; more to the point, the _DATA member doesn't have any of the session variables that I registered in PHP.
HOWEVER! When I use PHP::Session (and passing the same sess id to its constructor), THIS object does indeed find the session variables in question.
Ideally, I want to use CGI::Session since it seems to be more robust and PHP::Session seems to be a lot more task-specific, so can someone suggest where I'm going wrong with CGI::Session? (Should I create a PHP::Session and then try to pass it to CGI::Session?)
PHP::Session was designed to interoperate with sessions created in PHP. CGI::Session was designed as a Perl-only solution.
CGI::Session does offer multiple back-end implementations, so in theory somebody could write driver, serializer, and id modules for CGI::Session that would be compatible with PHP sessions. Nobody seems to have done that yet, though.

Reusing a Class Throughout Codeigniter Controller

I am coding my first CodeIgniter application (very familiar with PHP, but not CI) and have the following setup:
I have a controller, Signup, that controls a signup process. Every function of the controller is the next step in the process. I have an object, Did, that I am currently loading as a library. This object's properties/variables are updated as the signup process moves along.
The issue I'm having is that the properties from one function of the Signup controller do not carry over to the next function. It is as if the class is re-constructed with every function.
Is there a way to reuse the class throughout the controller without it having to be re-instantiated? I'd rather not have to serialize and store in a session, either.
Thanks in advance.
As always, there are many solutions to the same problem. Please disregard this if it doesn't fit well with your implementation.
Keeping the signup steps in an object is a good idea- however, every time you load a new page CI rebuilds all the objects. In order for data to persist it should be stored in the session, but that doesn't mean you have to be working with session variables in your controller.
How are you transferring data to your application? Is it via forms or ajax?
One way you can do it is by unserializing the object from the session and storing it as an object in your controller's constructor. That way you can still run $myObj->function() against it and use a $myObj->save() function to reserialize and store it.
Hope that helps!
The problem you are having is that you are depending on the in-memory state of your application to remain from request to request.
You're expecting your class to use the same instantiation of your Did object between requests.
This is not how PHP/HTTP works. Each request is handled individually and is it's own instance of your application. So each request creates a new Did object.
To persist the state you need to either use Sessions to carry information between requests, use a database to handle your persistent state, or a combination of both.
Codeigniter Sessions
Codeigniter Database Class

Categories