PHP pdo from database not loading [duplicate] - php

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()?

Related

Can I make a session alive after when user closes his browser?

I'm trying to implement a system to keep an user logged in for a while. I can do that by using cookies and storing it into database and then identifying him.
But recently I heard a session can be alive even when user closes his browser and opens a new window. I mean can a session still be available after closing/opening the browser again (or even multiple time)?
How much time (maximum) can I use $_SESSION["LoginValidation"] in following script?
<?php
session_start();
$_SESSION["LoginValidation"] = ture;
Currently that session will be available until closing the browser.
In order to make the session persist after closing the browser you need to set an expiry time for the session cookie. A cookie without an expiry time is deleted when the browser is closed, and is normally referred to as a session cookie (which is not the same thing as a PHP session - just related).
(side note: if your browser is configured to "save open tabs" at exit, then the session cookies may be saved by the browser even though they should be deleted)
So you could just set session.cookie_lifetime to a large value. But that doesn't stop the session data stored on your server from being deleted - to keep the data for longer you need to up the value for session.gc_maxlifetime.
BUT THIS IS THE WRONG WAY TO FIX THE PROBLEM
There are security and capacity implications to implementing such persistent sessions - you should certainly NEVER implement this as default behaviour - only where the user has explicitly given their consent.
Using a "Remember me" cookie as a sort of lightweight session system is the best practice solution. Give it a random value (suggest you use a reasonably reliable source of random numbers, e.g. base64_encode(openssl_random_pseudo_bytes(64)) and a name which does not conflict with other cookies, and store it along with the data you really want to persist across the actual sessions (e.g. authenticaticated username).
Approach 1) session.cookie-lifetime : This is the lifetime of the cookie, which by default is 0, which means the cookie is destroyed when the browser is closed. You can set a longer lifetime by increasing this variable.
It is relative to the server time, so you need to account for differences in the time in your clients' machine and your server's.
There's also session.gc-maxlifetime, which is the time after which the session data is seen as garbage in the storage and is destroyed.
While you can set these settings both to relatively high values and have it working, I would recommend against doing so, as this will leave a lot of unnecessary session data hanging around in your session storage, due to the GC not collecting actual dead session
Or
another approach is for session to make alive even after closing of browser save session in db and get its id , and set that id in user cookie via
setcookie("name","value",time()+$int);
so you can fetch that value from $_COOKIE["name"]; use it to get session variables from data base

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.

Does session_start in PHP prevent session expiration?

I'm somewhat bewildered about using session_start in PHP. Should I use it in my scripts both when user initially creates session and when resumes it on consequent queries - or only when creating?
Currently I do not call it when session already exists but I have found that session sometimes expires unexpectedly fast:
For example, from public log of my site I see:
srinivasvarma678 09:14:34 27-Jun-14
I've just logged in...
...
srinivasvarma678 08:59:38 27-Jun-14
I'm proud to tell I've just solved Vowel Count!
I.e. user's last interaction with site was at 8:59 and then in 15 minutes he needs to log in again (though session.gc_maxlifetime=1440)
Could this behavior be explained by the fact I am not calling session_start every time?
Short answer: Yes
As stated here in the PHP docs:
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.
So if you want to continue the session, you should always use session_start() on every page...
session_start() allows you to use sessions in your script.
You should use it both when creating new sessions or reusing existent one.
It also updates the session, to it won't be garbage collected and removed.

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.

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