php: cookie based sessions - php

does any body have any info/links as to how to integrate a cookie based session system? i've used file/mysql, and am currently using memcached. i wanted to play with apc sessions, but thought i'd give a go at cookies, only i don't know much about it.
i imagine i'd have to write my own session handler class?

In PHP session data is usually stored in a file. The only thing stored in the cookie is a session identifier. When sessions are enabled and a valid session cookie is found, PHP loads the users session data from the file into a super global called funnily enough SESSION.
Basic sessions are started using session_start(); called before any text is sent to the browser. then items are added to or removed from the session object using simple array indexing eg.
$_SESSION['favcolour'] = 'blue';
later...
$favcolour = $_SESSION['favcolour'];
basic cookie only sessions (no local storage) can be created with a call to
set_cookie('favcolour','blue'[,other params]);
before any text is sent to the browser, then retrieved from the cookie superglobal
$favcolour = $_COOKIE['favcolour'];
you don't need to call session_start() if doing cookie only sessions.
the optional [,other params] are more advanced and can be read about here http://www.php.net/manual/en/function.setcookie.php
Sessions can become a very complex discussion, I'd suggest doing some light work in them and then expand your knowledge.
DC
all you ever wanted to know about PHP sessions
http://www.php.net/manual/en/book.session.php
DC
To reuse PHP's session handling code you will need to add a write handler using session_set_save_handler and then do exactly nothing in that handler. That's because its called after the output to the browser is closed therefore you cannot send anything to the browser.
Before writing non header data to the browser use the set_cookie functions and store the contents of the $_SESSION array (after serialising and encrypting) into a cookie. when the applications start you can read the cookie unserialise it and put it into the $_SESSION array.
That's a quick hint at what to do as I have never done it, I prefer to write all my own cookie code. There may be some gotcha's but its not hard a few tests should find any gotcha's.
DC

Related

Is it possible to prevent php session from destroying when you close browser?

We want to use sessions instead of cookies for keeping track of a few things. However, when I close my browser, and I reopen a page to echo a session var, it doesn't exist (which is how it is suppose to be). Is it possible to prevent this from happening with some magic or anything?
This is not a duplicate question, all I see are people wanting to destroy sessions, I want to do the opposite and retain the session for as long as possible.
Any knowledge would be appreciated.
The right way of doing this is with a database, you can mimic or control php sessions and store them in a database instead of in a file ( as normal ). Then once you have control of the data you can base renewing session via the ip address or better yet by login.
So say a user logs in and then you need to store some data, you store that in the session but php will store it in your database table ( when configured correctly ). Latter the user comes back, initially any visitor would get a fresh session, however once they login you would be able to retrieve the past session they had. You generally don't have much control on if or when a client will delete expired cookies.
This topic is too extensive to put just a few pieces of example code but I did find this small article on the topic.
http://culttt.com/2013/02/04/how-to-save-php-sessions-to-a-database/
The guts of it is to use this function, session_set_save_handler
http://php.net/manual/en/function.session-set-save-handler.php
Once you have control of the data you can do whatever you want, however I would caution you about relying only on the IP address and it would be preferable to use a login system for something like this to prevent serving the session up to the wrong visitor.
You cannot reliably control what happens on the client side, even using a separate cookie would not be reliable and would have the disadvantage of storing data on the client where it could be accessed instead of keeping it on your server. Sessions are controlled by cookies but the data in them remains on your server, the cookie just identifies the client.
As a side note, I personally dislike using sessions at all. It may be possible to store what you need in the url, then it can be bookmarked. The classic example would be input for a search form ( via $_GET ) or for paging purposes. There is nothing wrong with doing this if it's not secure data. The problem with sessions is if the data is for a page such as my "classic example" or for paging you get only one session, so you would only be able to have one set of search data at a time, in the url you could have several sets of search data open at once. That said it does largely depend on what you need to save or persist.
Reset the session cookie manually.
$lifetime=60*60; // duration in seconds
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);
You can use session.gc_maxlifetime and session_set_cookie_params, i.e.:
// server should keep session data for AT LEAST 1 Year
ini_set('session.gc_maxlifetime', 3600 * 24 * 365);
// each client should remember their session id for EXACTLY 1 Year
session_set_cookie_params(3600 * 24 * 365);
session_start();
Note:
You can also change the session options globally by editing php.ini -
Session configuration options
PHP sessions use session cookies. Browsers have their own ways of dealing with them but they all consider them to be trash if you close the browser.
Session cookies are not and can not be made persistent. If you need persistent cookies, just use a regular cookie to save a user identification code that your server would recognize, and save their session information in a database or flat file indexed on that id code.
Note that accumulating sessions on the server progressively causes important performance and security concerns.
Note on other answers: All of them mention ways to extend the session cookie expiration which will not overcome the regular behavior when you close your browser window.

How does php know to start a new session

PHP will start a new session if a browser is closed and reopened.
The old session file is still kept in the session save directory, but a new session is started.
What does php look for in the browser to know that it must start a new session?
I guess what i am really asking is, what exactly does session_start() do under the hood
To simply answer your question, it looks for a cookie called PHPSESSID and if no cookie is supplied in the request, a call to session_regenerate_id is made to initialize the cookie value.
The cookie is then persistently used throughout the lifetime of the browser.
Unless other settings apply, this is a stripped down version of the default behavior.
The cookie containing the session id is set without an expiry by default. This means it will expire when the browser is closed. So the session will be lost at that point since the client won't have the old session ID anymore.
All you want to know is already written here: http://www.php.net/manual/en/function.session-start.php
session_start() creates a session or resumes the current one based on
a session identifier passed via a GET or POST request, or passed via a
cookie.
When session_start() is called or when a session auto starts, PHP will
call the open and read session save handlers. These will either be a
built-in save handler provided by default or by PHP extensions (such
as SQLite or Memcached); or can be custom handler as defined by
session_set_save_handler(). The read callback will retrieve any
existing session data (stored in a special serialized format) and will
be unserialized and used to automatically populate the $_SESSION
superglobal when the read callback returns the saved session data back
to PHP session handling.
Basically, PHP writes a special file in the file system (usually in the /tmp directory) and gets the data from there.
The session ID (PHPSESSID) is saved in a cookie in the users browser. If none is found/one is invalid it creates one. The image below may be of some help in understanding what you want to know (it's from Chrome).
Once PHP gets this session ID, it looks for the corrisponding session which is stored in the session save_path (normally /tmp on unix machines). It then gives you the ability to access the information stored in that session file using the $_SESSION superglobal.
The cookies are stored only if there is nothing outputted on the PHP page prior to the session_start() call. If there is something being outputted, the cookie is not stored and you need another method(as mentioned, SQLite or MySQL) to store those UNIQUE values and recognize and separate each user.

SESSION variable reset when changing page [duplicate]

Why I can use setcookie without any preparation while need a session_start() before using $_SESSION?And I think works they do are similar.
Because setcookie() defines a cookie to be sent along with the rest of the HTTP headers. That's a completely different thing than what session_start() does, e.g. creating a session or resuming the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
The first just adds something to the header and sends it to the browser, while the other gets the Session ID from $_COOKIEs or $_GET or $_POST and then tries finding the session file in the session_save_path and when found unserializing the values of it into $_SESSION and if not, create a new session, probably using setcookie in the process to set the Session Id.
See the chapter on Sessions in the PHP Manual.
Edit Like #Felix correctly points out below, the session is not necessarily saved in a file. It's not that important though, because the argument stays the same: session_start will find and (re-) initialize your session data, while setcookie just does what the name implies.
For explanation see the reply before mine.
If you just don't want to call the start_session() function have a look at this setting in the php.ini:
session.auto_start
The session data is not necessarily stored in a file as Gordon says. With session_set_save_handler() you can define your own backend that should store the values, e.g. in a database.
All this data retrieving is handled with session_start(). This way you can easily change you backend without breaking your application.
Note: This is only one reason for session_start(), and again it does lot more then just setting cookies.
The session data is not necessarily stored in a file as Gordon says. With session_set_save_handler() you can define your own back end that should store the values, e.g. in a database.
All this data retrieving is handled with session_start(). This way you can easily change you back end without breaking your application.
Note: This is only one reason for session_start(), and again it does lot more then just setting cookies.

Conceptual understanding of PHP server session

So as a engineer, I usually require a concert understanding to be able to work with something. I feel like I understand the basics of a session. I am wondering about the specifics and details there of.
What are the limitations of a session?
How can I manipulate a session? What can explicitly not be done to or with a session.
What data structures does PHP use to define and manage sessions?
Is a PHP session different from any other session in any significant way?
I understand that these questions are general, so if anyone can simply suggest a good resource I would be thankful. There is plenty of info out there, but it is either too basic or teaching to a specific topic.
Thank you for the help.
Sessions is a way for the server to recognize you so he sends to you a customized version of the page instead of sending always the same page for everybody.
To recognize you one way is he tells the browser to save in your computer a small file with a simple text, and when you visit the page again the server would ask the browser for that file, if the browser sends it, and it contains the expected content, the server can now know this is you again. That are cookies.
Another way to maintain a session, a part from cookies, is the server puts a special unique token for you in the url of all the links the page has. Whenever you browse the site all pages you visit will have that token, the server see it and know it's the token it made to you, so he knows it's you again.
So both with cookies or url-based sessions, the server will have to save info about the sessions opened, for example to store the $_SESSION variables you create in PHP, if you create such a variable the server will save it to a file which he will later identified by your cookie or token content and when you re-visit the page he will read that file and load the $_SESSION variables you create last time.
Here's a good resource: http://php.net/manual/en/book.session.php
What are the limitations of a session?
I don't really know what you mean by that. Limitations in what context?
How can I manipulate a session?
To manipulate values, just use the $_SESSION superglobal directly.
What can explicitly not be done to or with a session?
Again, without context, it's hard to understand what you mean. I guess an important point is that sessions are transient, so you can't explicitly store data you want to keep indefinitely.
What data structures does PHP use to define and manage sessions?
The filesystem.
Is a PHP session different from any other session in any significant way?
What is another session?
http://php.net is the best source for your questions
PHP session is a very nice way of having persistent information on your site for different users.
Check out the PHP session functions you can use.
You can view examples of how to use sessions at php.net.
A session is most commonly associated with user accounts. A user can log into your site, and you create a user session to keep track of their information and make sure they are allowed to be logged in.
The basic assumption is that a session is secure, because the server is aware of the sessions in progress. Utilizing sessions over HTTPS is a fairly secure way of keeping users logged into your site (without HTTPS you run the risk of session hijacking).
The other basic function is to have persistent data about a given user. So let's say you wanted to keep track if the user has submitted a form, you could do:
$_SESSION['form_submitted'] = TRUE;
And now you can check that global variable whenever you want to know if that specific user has submitted the form. So the session (in the same way a cookie is used) allows you to do really cool things that otherwise would not be possible.

In PHP will a session be created if a browser is not used

I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However, it seems that when clients try to connect through non-browser methods such as Curl or wget, the state information is not being preserved.
Will a PHP session only be created if a browser is requesting the page? I am explicitly starting the session with session_start() as well as naming it before hand with session_name().
An added note. I learned that one of the major problems I was having was that I was naming the session instead of setting the session id via session_id($id); My intention in using session_name() was to retrieve the same session that was previously created, and the correct way to do this is by setting the session_id not the session_name.
It seems that session information will be persisted on the server as noted below (THANK YOU). But to keep this you must pass the session id, or, as in my case, any other id that would uniquely identify the user. Use this id as the session_id and your sessions will function as expected.
Session Cookies
Remember that HTTP is stateless, so sessions are tracked on your server, but the client has to identify itself with each request. When you declare session_start(), your browser is usually setting a cookie (the "PHP Session Id"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a "session" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name.
All of this is to say that cookies are playing an active role in your sessions, so if the client doesn't support cookies, then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating.
If cookies aren't an option for your client, you're going to have to find another way to pass a session id to the server. This can be done in the query string, for example, although it's a considered a bit less private to send a session id in this way.
mysite.com?PHPSESSID=10alksdjfq9e
How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the PHP website.
Sidenote: Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns.
Sidenote: #Uberfuzzy makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some "cookie awareness" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the curl manual.
If you call session_start(), then a session will be created if the client isn't in an existing one. If the client doesn't support (or is configured to ignore) the cookies or querystring mechanism used to maintain the session, a new session will be created on every request.
This may bloat your session storage mechanism with unused sessions.
It might be a better idea to only call session_start() when you have something to store in the session (e.g. user login, or something else that robots aren't likely to do), if you feel this is likely to be a problem.
Will a PHP session only be created if a browser is requesting the page?
Short answer: Yes. Sessions were created specifically to solve the HTTP stateless problem by leveraging browser features. APC, memcached, DB, etc. don't matter. Those are just storage methods for the session, and will suffer from the same problem.
Longer answer: The concept of sessions were created to account for the fact that HTTP is a stateless protocol, and it turns out that state's pretty important for a wide variety of software applications.
The most common way of implementing sessions is with cookies. PHP sends the session ID in a cookie, and the browser sends the cookie with the session ID back. This ID is used on the server to find whatever information you've stored in the session. PHP has the capacity to include and read a session ID at the end of a URLs, but this assumes that users will navigate to pages on your site/application by clicking links that include a generated session ID.
In your specific case, it is possible to use cookies with curl (and possibly wget). Curl is a web browser, just one without a GUI. If it's the command line curl program you're using (as opposed to the C library, PHP extension,etc.) read up on the following options
-b/--cookie
-c/--cookie-jar
-j/--junk-session-cookies

Categories