Laravel global variable for real-time application? - php

I'm developing an application that will need to provide certain state to users in real time. Every user will use an AJAX script to 'watch' that state - every user will see all of the shared state. I'm concerned about security, since some of the shared state are secretive data.
I've tried to implement this with environment variables in .env, but I need arrays and I think .env is not compatible with arrays.
I've also tried using globals without success.
My final attempt was to use a config file and the config helper from laravel, but changes to the state weren't saved! I have thought about using a database table, but I don't know how to make it safe.
How should I approach this problem?

Related

Storing Session ID in AWS S3 or couchbase. Good idea?

I'm going to introduce the Round Robin Load Balancing in our architecture and I don't really want to use the Sticky Session since we don't utilize the cookie in our apps. I'm trying to decide whether I should store the session ID for my php apps inside the couchbase database or I should store it in the mounted AWS S3. Currently our session ID is stored in a pretty standard way which is local server.
I'm thinking of moving the session id storage in the couchbase database, however that requires us to change the code to accomodate that capability. Storing the session ID on mounted AWS S3 is preferable since I don't really have to change anything in my code other than the pointer in php.ini. But is it a good idea though and does it has any performance implication to it. Anyone has any experience with this feature request and perhaps can share your thought/result?
Many thanks everyone...
Deciding on how to implement sessions based on what is easy to implement doesn't seem like a very sound basis for choosing an architecture.
S3 -- particularly if you are already using it in a way in which it is not exactly designed to be used (by mounting it, to emulate a filesystem, which it is not -- it's an object store) -- does not seem like an appropriate platform for storing session data, for two reasons: the first is the likelihood of potential performance issues, and the second is the consistency model of S3. A third potential consideration is the per-request pricing for S3, and a fourth consideration is that you'd need to disable any local file cache from s3fs (assuming that's what you're using) or you run the risk of reading stale data... but this would likely introduce additional potential performance issues.
When you create a new object in S3, and then try to download it, it will not necessarily be immediately available in the US Standard Region, which only provides eventual consistency, which means it is sometimes but not always possible to immediately download something you just finished uploading. The other regions provide read-after-write consistency on new objects, but this could potentially come in the form of a tradeoff that increases the time it takes to initially create the new object, or the initial time to fetch it again.
In contrast to new objects, all regions, not just US Standard, provide only eventual consistency when you overwrite an existing object with different content. This means if you change the contents of a file on S3 and immediately read the file again, you may not immediately see the newest version of the file... and that if you delete a file and subsequently try to read from it again, you might actually be able to, for a short period of time. Testing this to disprove whether this is a problem would serve no purpose, since this is their stated consistency model, and behavior you observe today could deteriorate in the future yet still be consistent with their model.
http://aws.amazon.com/s3/faqs/
By contrast, SimpleDB, DynamoDB, and RDS all provide services that are more appropriate for storing session data, with the applicability of each of these services depending on your specific requirements.
Or, you could store the sessions in Couchbase, if that provides suitable performance. I can't comment on that possibility, since I am unfamiliar with that platform... but S3, in spite of being an excellent service, it does not seem well-suited for this application.
One thing, though...
we don't utilize the cookie in our apps
I'm skeptical, since that's typically the way sessions work. How does your server identify the appropriate session for the user connecting to your site, then, if not by a cookie?

What are the alternative to PHP session variables?

I am writing a brand new website and I'd like to make sure that it scales out easily if I ever get to the point where I must host the site on multiple machines with a load balancer.
The user of the website can be authenticated. In other words, I need to maintain some state information. My first reflex was to use Session variables but then I am going to be limited to a single machine. I know that there are ways to store the session variables outside (in a DB, redis, memcached) but is that the only options?
What are the alternative to session variable? How Facebook and other big web sites are doing this?
P.S. I am not looking for another session handler (DB, redis, etc.). I'd like to know if there a way to completely get rid of session variables.
Ever heard of session_set_save_handler? It allows you to use mechanisms other than the default PHP session handler (the one that writes sess_xxxxxxxxxxxx files in tmp directory).
You can write your own session handler that uses a database. This could be a time consuming task; so you can stick with the default PHP session handlers for the time being and transparently switch to database when you are ready. You probably won't have to rewrite any code except implementing and plugging in your version of the six session handling functions.
You can look into caching, i.e using Zend cache or APC cache, for example.

PHP sessions, cookieless domains, and performance

I'm on board with the whole cookieless domains / CDN thing, and I understand how just sending cookies for requests to www.yourdomain.com, while setting up a separate domain like cdn.yourdomain.com to keep unnecessary cookies from being sent can help performance.
What I'm curious about is if using PHP's native sessions have a negative effect on performance, and if so, how? I know the session key is kept track of in a cookie, which is small, and so that seems fine.
I'm prompted to ask this question because in the past I've written my web apps and stored a lof of the user's active data, preferences, and authentication information in the $_SESSION variable. However, I notice that some popular web applications out there, like Wordpress, don't use $_SESSION at all. But sessions are easy to use and seem fairly secure, especially if you combine it with tracking user-agent / ip changes to prevent session hijacking. So why don't Wordpress and other web apps use php's sessions? Should I also stop using sessions?
Also, let me also clarify that I do realize the server must load the session data to process a page request, but that's not what I'm asking about here. My question is about if / how it impacts the network performance, especially in regard to the headers being sent / received. For example does using sessions prevent pages or images on the site from being served from the browser's cache? Is the PHPSESID cookie the only additional header that is being sent? These sorts of things.
The standard store for $_SESSION is the file-system with one file per session. This comes with a price:
When two requests access the same session, one request will win over the other and the other request needs to wait until the first request has finished. A race condition controlled by file-locking.
Using cookies to store the session data (Wordpress, Codeigniter), the race-condition is the same but the locking is not that immanent, but a browser might do locking within the cookie management.
Using cookies has the downside that you can not store that much data and that the data get's passed with each request and response. This is likely to trigger security issues as well. Steal the cookie and you've got the data. If it's encrypted, an attacker can try to decrypt it to gain the data stored therein.
The historical reason for Wordpress was that the platform never used the PHP Sessions. The root project started around 2000, it got a lot of traction in 2002 and 2004. As session handling was only available with PHP 4 and PHP 3 was much more popular that time.
Later on, when $_SESSION was available, the main design of the application was already done, and it worked. Next to that, in 2004/2005 wordpress decided to start a commercial multi-blog hosting service. This created a need in scaling the application(s) across servers and cookies+database looked more easy for the session/user handling than using the $_SESSION implementation. Infact, this is pretty easy and just works, so there never was need to change it.
For Codeigniter I can not say that much. I know that it stores all session information inside a cookie by default. So session is just another name for cookie. Optionally it can be encrypted but this needs configuration. IIRC it was said that this has been done because "most users do not need sessions". For those who need, there is a database backend (requires additional configuration) so users can change from cookie to database store transparently within their application. There is a new implementation available as well that allows you to change to any store you like, e.g. to native PHP sessions as well. This is done with so called drivers.
However this does not mean that you can't achieve the same based on $_SESSION nowadays. You can replace the store with whatever you like (even cookies :) ) and the PHP implementation of it should be encapsulated anyway in a good program design.
That done you can implement a store you can better control locking on (e.g. a database) and that works across servers in a load balanced infrastructure that does not support sticky sessions.
Wordpress is a good example for an own implementation of sessions handling totally agnostic to whatever PHP offers. That means the wheel has been re-invented. With a view from today, I would not call their design explicitly innovative, so it full-fills a very specific need in a very specific environment that you can only understand if you know about the projects roots.
Codeigniter is maybe a little step ahead (in an interface sense) as it offers some sort of (unstable) interface to sessions and it's possible to replace it with any implementation you like. That's much better for new developers but it's also sort of re-inventing the wheel because PHP does this already out of the box.
The best thing you can do in an application design is to make the implementation independent from system needs, so to make the storage mechanism of your session data independent from the rest of the program flow. PHP offers this with a pretty direct interface, the $_SESSION array and the session configuration.
As $_SESSION is a superglobal array you might want to prevent your application to access it directly as this would introduce global state. So in a good design you would have an interface to it, to be able to fully abstract away from the superglobal.
Done that, plus abstraction of the store plus configuration (e.g. all in one session dependency container), you should be able to scale and maintain your application well over as many servers as you like for whatever reason. Your implementation then can just use cookies if you think that's it for you. However you will be able to switch to database based session in case you need it - without the need to rewrite large parts of your application.
I'm not 100% confident this is the case but one reason to avoid the built-in $_SESSION mechanism in PHP is if you want to deploy your web application in a high-availability web farm scenario.
Because the default session behavior in PHP is to store session objects in process, in memory, it makes it hard (if not impossible) to have multiple servers processing requests from the same user. You would only have this if you wanted to deploy your web application in a web farm environment where you have a number of PHP web servers processing requests for your app to balance the load.
So, while in-process session state is generally much faster than a database-based solution, the latter is favorable when you need to process a huge number of requests and to service the capacity a web-farm environment is used.
As I said in the beginning, I'm not 100% sure if PHP supports configuring the session state provider to be a database, or session state server, instead of the in-process default.

Are there limitations in PHP session handling?

I've seen many sites give up the use of the default handling of sessions in PHP for their own method and I still have no clue why.
They are definitely running PHP and it just seems pointless to me that people would design their own method. Is there some sort of limitation that I do not know of or is it purely so they have control of everything?
(I tried asking them and yeah they either didn't have a way of contacting them or they "saw something somewhere against using PHP sessions" without knowing what it actually was)
Default sessions are stored on the hard drive, usually in the /tmp directory.
When your site gets larger, 1 computer isn't sufficient to run it.
Therefore, people resort to load balancing (among other solutions).
Load balancer effectively switches between a cluster of computers. Therefore, if by any chance you got served by computer #1 on your first request and then by computer #2 at your second request - the second computer cannot read the session since it's not in its /tmp folder.
This is a simplified scenario of course since there's much more to application scaling but this is one of the reasons why people resort to overriding the default session mechanism.
The other thing of interest is storing sessions in the db thus making them searchable and what not. You can also create an interface for effectively forcefully logging people out, which is something that the default mechanism cannot provide.
I would have thought a principal reason for rolling your own session-handling functionality is for the purposes of testing. If you're running unit tests, you won't necessarily have a browser environment going. You won't be able to set cookies, and so PHP won't set $_SESSION variables for you.
If, however, you wrote your own session handling class(es), then you could create a mock class for running unit tests. The object would behave like a "real" session, but you won't have to faff about with browsers, cookies and human beings.
Well with the standard setup you are tied to using the file system, saving session data unencrypted etc.
Writing your own session handling using session_set_save_handler you can adjust the sesssion management to your needs ... applying encryption, saving session in a database, synchronizing the sessions with separate software systems ...
1) Session are still widely used. They works and do the work, so there is not point to change it unless a special case.
2) However, Session is weak, it relies in a single PHP (that can be stolen). However, it is possible to protect a session using different method such cookie + ip + expiration.
So yes and no. Session are still widely used but require a fine tune.

Is there a PHP/MySQL database admin that doesn't use sessions?

I am doing development work on a site with a strange server set up where sessions basically don't work. It's kind of a long story, but the main crux is it's a cluster of servers that are syncronized from an FTP server every few minutes. And for example, anything written to the filesystem in PHP gets deleted within 5 minutes.
So this means sessions don't work and I get some strange problems in phpMyAdmin, like it forgetting which page of a table I was on - I click 'next page' and end up back at the start again.
I've also tried SQL Buddy and am getting similar problems.
Are there any equivalents that don't use sessions? Doesn't need to be as full-featured as PMA, it's mainly for adding/editing some stuff.
There's always the MySQL GUI Tools.
You can make phpmyadmin use other authentication methods:
http://www.phpmyadmin.net/documentation/#authentication_modes
Depends how much security you need and how restricted you are, but 'config' authentication mode with a custom .htaccess sounds like it might work for you.
I don't know how hard it would be to plug this into phpMyAdmin, but PHP has a functionnality that allows sessions to be stored in another way than using files.
In your case, you already have a database server, obviously, so maybe you could create a "technical" database, and use it to store sessions ? This way, you would still be able use phpMyAdmin (which is quite a good tool), but your problem should be solved.
The PHP function you need to know to do that is session_set_save_handler :
session_set_save_handler() sets the
user-level session storage functions
which are used for storing and
retrieving data associated with a
session.
This is most useful when a
storage method other than those
supplied by PHP sessions is preferred.
i.e. Storing the session data in a
local database.
There are a couple of examples (take a look at the comments at the bottom of the page : some might be helpful)
For instance, Drupal uses this solution to store sessions into DB instead of files, by default.
Another solution would be to use memcached to store your sessions -- of course, if you don't have a memcached server at your disposal, this might be a bit harder than storing them in DB ^^
Or, of course, if you have access to your DB server via the network, you could install phpMyAdmin on your local computer, or use a tool like MySQL GUI Tools and its MySQL Query Browser.
I found a neat solution! SQLBuddy has a feature where you can put the password in the config file and it will use it automatically without a need to log in.
Obviously this is insecure by default, but coupled with a .htaccess and .htpasswd (which does work on the server) I've now got a secure login.

Categories