How does php know to start a new session - php

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.

Related

PHP pdo from database not loading [duplicate]

I am trying to echo each active session that has been active in the past 15 minutes, I check using the following code to log their last seen time.
$_SESSION['last_seen'] = date("Y-m-d H:i:s");
But I receive these errors when doing the below code, which the code above this text.
Notice: Undefined index: last_seen in
C:\xampp\htdocs\hk\templates\default\index.php on line 249 Warning:
Illegal string offset 'last_seen' in
C:\xampp\htdocs\hk\templates\default\index.php on line 249
<?php
foreach($_SESSION as $s){
if ($s['last_seen'] >= date("Y-m-d H:i:s", strtotime("-900 seconds")))
{
echo $s['username'];
}
}
?>
Long story short:
1) First of you need to recall session_start() every time (if you haven't).
2) You can't read from other sessions with PHP's native session handler. You would need to implement your own session handler.
I guess you just started using PHP.
So here are some basic explanations you need to know about the web, PHP, sessions and cookies:
Cookies: Cookies are small information and sent to the client's browser when the page is loading. If the browser accepts the cookie (which is NOT always the case), he's sending that cookie information on every request.
so... doing something like
<?php
setcookie('my_cookie', 'Hello World!', time() + 60 * 60);
If the client is requesting that page and the code above gets executed, the clients browser is asked to store a cookie from your_domain.com with the name 'my_cookie', containing 'Hello World!'
Assuming the browser has accepted that cookie, he will be sending it on every page load against your_domain.com - as long as the cookie hasn't expired.
This allows you to store small, textual information on the clients side and you will be able to retrieve and read on later requests with $_COOKIE['my_cookie'].
So what has this to do with sessions? Without cookies we won't be able to track a client. PHP application loses session information between requests.
If the client stumbles on your page, invoking the first time session_start(), PHP will create a Session Cookie with a unique ID and allocates somewhere on the filesystem space for data, stored in $_SESSION. This is called a "session storage". So you could start writing data to $_SESSION like $_SESSION['last_seen'] = date("Y-m-d H:i:s");. The browser will send that cookie every time to your server on the next several requests. Recalling session_start(), PHP is now aware of that a session cookie has already been set and reads that ID. If the ID matches against the session storage, previously generated, the $_SESSION var will be populated and you could read the value of $_SESSION['last_seen']
You thought with $_SESSION you would access all the session information from any user, but that's wrong. The session store will just give you that client's session id specific data.
As I mentioned before you can't access any other session data with PHP's native session handler, however you could implement your own session handler.
Most people who start writing their own session handler tend to use a MySQL database as their session storage. I prefer using Redis.
This may help you:
Basic PHP session tutorial: http://www.phpro.org/tutorials/Introduction-To-PHP-Sessions.html
Writing your own session handler and using MySQL: http://culttt.com/2013/02/04/how-to-save-php-sessions-to-a-database/
I think you don't understand $_SESSION global array. It contains data only for current session of user (not for all users of your site). You should save this data in memcached or database.
I suggest you actually try to echo "<pre>"; print_r($_SESSION); echo "</pre>" for troubleshooting purposes - this will tell you the structure of the session array.
PS: I trust you have started the session with a command session_start()?

Session is handled by server or language?

i am working on PHP and i know how to manage the session. But my question is, session is related to language or web server. Who is responsible to execute the session?
You are responsible for session execute by starting the session with session_start().
By default session is stored in /tmp on a Linux/Unix system. You can change it with session_save_path() method.
Also take a look in php.ini for [Session] part, it should look like this
; Handler used to store/retrieve data.
; http://www.php.net/manual/en/session.configuration.php#ini.session.save-handler
session.save_handler = files
As You can see by default it is stored as file storage, it's recommended to move session to cache i.e. memcache.
EDIT:
Maybe this post can help You: https://security.stackexchange.com/a/19054
A session token is a unique identifier that is generated and sent from a server to a client to identify the current interaction session. The client usually stores and sends the token as an HTTP cookie and/or sends it as a parameter in GET or POST queries. The reason to use session tokens is that the client only has to handle the identifier—all session data is stored on the server (usually in a database, to which the client does not have direct access) linked to that identifier. Examples of the names that some programming languages use when naming their HTTP cookie include JSESSIONID (JSP), PHPSESSID (PHP), CGISESSID (CGI), and ASPSESSIONID (ASP).
Sessions are a combination of two components, namely, a client-side session ID and server-side session data. well, practically it behaves like a cookie, 2 cookies which reply on each other. The Client-side can send a session ID to the server-side as a URL param, cookie, or even HTTP headers. The server then uses this session ID to find the matching session data to return to the requesting client.
so to answer your question straight up, a session is part of both the server and the client, which you maybe refer to as language. But PHP handles the execution.
additionally, You can tweak session behavior via the various session functions.
Session is generated by server but it is coupled with the language. So if you look into your browser resource you'll find your session id prefixed with the language you are using.

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.

can session variables survive from php -> html -> php?

the question is really simple, but i searched it many different ways and the results were not related to my question.
so if i have a session variable in a php file if i open an html page after that and then a php file again, will i be able to retrieve the data ? or do they all have to be adjacent?
I tried php->html->php but i couldn't get the variables on the other side. maybe Im doing something wrong.
Thanks in advance
Not 100% sure what you mean, but if by "open" you mean in the browser, the calls do not need to be adjacent. You just need to do a session_start() in every PHP script in which you want to use session data.
Adjacency is not something that is really relevant for this question.
in PHP way of things, sessions are essentially files that contain serialized data on the server. The browser that called a script containing session_start() call receives a special token that identifies the session on the server, and it is normally (though not necessarily) stored as a cookie.
This effectively means that any php script that uses session_start() and receives a session id (via cookie or otherwise) will read and could use session data, unless it was removed from the server file system between the calls, or the session has expired (frankly, I'm not sure whether PHP removes the expired sessions on the server side).
Accessing anything outside of this model with the browser (html page, or even other sites) will not affect it in any way, unless these actions change or remove session id.
yes...session variable can survive php->html->php.
But on every php page ...very first line should be session_start()
This easy way (I guess): Set a cookie storing the session ID on the first php page. This way, every other php page can access the session ID and use it to restore the stored data, not matter how many (even foreign) pages were in between.

php: cookie based sessions

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

Categories