Is there a downside to session.auto_start in PHP? - session

I usually end up adding session_start() to the top of every page on my PHP sites (or in a header file which is in turn included on every page). I recently discovered that you can have sessions start automatically by using the following setting in php.ini:
session.auto_start = 1
What are the potential downsides (if any) of using this setting?

If you turn on session.auto_start then the only way to put objects
into your sessions is to load its class definition using
auto_prepend_file in which you load the class definition else you will
have to serialize() your object and unserialize() it afterwards. See.

Maybe this helps. It will create a session if there is no session created on page load.
if(!isset($_SESSION)): session_start();endif;
If you want to start a specific session, then use something like this:
if(!isset($_SESSION['your_session'])){
$data = array('default data');
$_SESSION['your_session']=$data;
}

Related

Laravel session key changing the whole time?

I am using "file storage" for my session. When I run this:
Session::set('awesomekey', 'myVal123');
And refresh the page, I can see new files being created in /storage/session each time. I assumed it would update the same file each time. This basically means sessions don't work at all. In other words, if it keeps recreating a session file, this never works:
Session::get('awesomekey');
Or at least, it returns a blank. What am I missing that could possibly be causing a new session key to be created each time a page is loaded?
UPDATE
On further investigation, it seems the cookie is regenerated on each page load. What could be causing that?
I am not even looking at logging in yet, so this information is useless to me --> http://willworkforbanjos.com/2014/02/laravel-sessions-not-working-in-4-1/
My problem is happening when I simply put the above set and get code in the master.blade.php file. It should set it, store the info, and on the next reload get the right information from session. But it can't because on reload it changed the cookie to some other code.
Anyone know why this is happening?
UPDATE 2
Adding: 'lifetime' => 120 to session.php did not work. (#Sheikh Heera)
Placing the code in the controller only, does not work. (#Phill Sparks)
I tried chrome and firefox, same result (#The Shift Exchange)
Just to be clear on what I'm trying to do. I add the following code in HomeController.php:
public function index()
{
Session::put('awesomekey', 'myVal123');
return View::make('home.index');
}
Then I put this in my master.blade.php:
print Session::get('awesomekey');
I do not include any "dies" or random echos in my controller side of the code, except for this. When I open the file the first time, I can see myVal123 being printed out.
I then take out this part in the controller:
Session::put('awesomekey', 'myVal123');
And reload the page. It now prints nothing. I can see in my browser that the cookie has changed. Generating a new cookie will lose the reference to the session, so I'm stuck trying to understand why it's doing that each time, even though it saves the session on the first load.
Any more ideas?
UPDATE 3
I also tried:
Running "php artisan dump-autoload" ... still doesn't work
I went here: http://www.whatismybrowser.com/are-cookies-enabled ... and yes, cookies are enabled.
I'm really running out of ideas here...
UPDATE 4
I went to SessionManager.php and just underneath this:
$lifetime = $this->app['config']['session.lifetime'];
I printed out the value of life time:
print $lifetime; die();
And this code was never hit on page reload?! However, adding this in my controller:
$d = Config::get('session.lifetime');
print $d;
Does in fact print out my value for lifetime.... :(
The problem was this line:
'cookie' => 'xxxx.com',
in session.php. Apparently it loses the cookie if you have a "." in the cookie name. I can't believe Laravel doesn't like that. Or maybe it's browser's in general.
I believe you are using:
'lifetime' => 0 // number of minutes
in your app/config/session.php file. Make it something like this:
'lifetime' => 120 // number of minutes or whatever you want
It'll work. I tried same settings as you described and just used 0 and I get same result, each time a new file is being created but once I change it to 120 or so, it works. So, it make sense that, if it's set to 'lifetime' => 0 in the session config then every time it just creates a new file for a new session because the session doesn't live. So, go to your app/config/session.php file and you'll find something like this, change the value:
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
Update:
You may use following code to get the lifetime value set in the app/config/session.php file:
Config::get('session.lifetime');
Have a look at the cookie's expire time in Chrome developer tools, or Firebug. If it is set to 0 then the cookie will expire immediately.
Also, double-check if your clock is setup correctly - strange things could happen if there's a disparity between your host's and the browser's clock. Make both systems consult NTP to ensure this is not an issue.
I had a similar problem with the sessions, if you're using the model User and your users table doesn't have the primaryKey as Id, you must overwrite that variable at the model.
class User extends Eloquent {
protected $primaryKey = 'admin_id';
}
In /app/config/session.php check the "HTTPS Only Cookie" setting.
Make sure it's "secure => false" if you are not using SSL!
I've experienced issues related to this. The session file wasn't created every time but sometimes I just can't get the session variable displayed. After hours of experiments I found that the problem was related to Debugbar.
If you're using Debugbar and having session issues, disable it and try again to confirm.
Use Session::put('value') instead of set.
http://laravel.com/docs/session#session-usage

How to update specific cached route?

I am running a Symfony2 app and I have a question about caching.
There is a comment on an answer here in SO that says:
you could create a command that only updates this one cached route. or
maybe consider using a kernel event listener that newly registers the
route on every request if you can afford the performance impact.
How could I update only this one cached route?
Where are cached routes stored?
The cache classes for url matching/generation can be found in app/cache/environment and are called appEnvironmentUrlGenerator.php and appEnvironmentUrlGenerator.php with "environment" being one of dev,prod, .. etc.
API reference:
http://api.symfony.com/2.3/Symfony/Component/Routing/Matcher/UrlMatcher.html
http://api.symfony.com/2.3/Symfony/Component/Routing/Generator/UrlGenerator.html
How does it work?
The router service receives a url-matcher and a url-generator when being constructed. Those are then being used inside the match() and generate() methods of the router.
https://github.com/symfony/symfony/blob/2.3/src/Symfony/Component/Routing/Router.php
For warming up the cache the RoutingCacheWarmer uses the router's warmUp() method (if it implements WarmableInterface).
Everything written by nifr is true, but doesn't really help you.
Symfony's built in router designed to support 'static' routes, so on the first cache warmup the routes will be generated and cached. If you check the mentioned cache files you will see that the routes saved in a static private variable.
There is no simple way to update a route (or change routes).
Using Symfony2 CMF
This a bit complex solution for your simple problem: http://symfony.com/doc/master/cmf/index.html
Clearing (invalidating) the cache
If you check the CacheClearCommand you will see that the implementation is quite complex. Some suggest to delete the whole cache dir, which I don't recommend, it is quite heavy and makes your site hang on until the cache is regenerated (even you can get exceptions of missing files / and logged out users if the sessions saved under the cache folder)
Calling the cache_warmer warmup has no effect if the cache already delegated.
If you just remove the two related cache file and then call the warmUp on the router would be a better solution, but also not nice one..
$cacheDir = $this->container->getParameter("kernel.cache_dir");
// Delete routing cache files
$filesystem = $this->container->get('filesystem');
$finder = new Finder();
/** #var File $file */
foreach ($finder->files()->depth('== 0')->in($cacheDir) as $file) {
if (preg_match('/UrlGenerator|UrlMatcher/', $file->getFilename()) == 1) {
$filesystem->remove($file->getRealpath());
}
}
$router = $this->container->get('router');
$router->warmUp($cacheDir);
Override the default Router class
As of 2.8 the Router class is defined with a parameter router.class
See here: https://github.com/symfony/framework-bundle/blob/v2.8.2/Resources/config/routing.xml#L63
Add something like this to your config.yml
parameters:
router.class: "My\Fancy\Router"
You can implement your own Router class, extending the original Router, and also you will need to extend the UrlMatcher and UrlGenerator classes to call the parent implementation and add your own routes to match against / generate with. This way you don't need to refresh the cache, because you can add your routes dynamically.
Note: I'm not sure if you can rely on this on long term, if you check master, the definition has changed, the parameter is not there anymore:
https://github.com/symfony/framework-bundle/blob/master/Resources/config/routing.xml#L54

Extending Joomla 2.5 Banner Component

I really hope someone can help me.
I need to be able to serve banners in categories which are dependant on a session variable - and can't find a component which does that. So I'd like to extend the Joomla Banner component in order to select banners based on a session variable which contains the category path.
The correct session variable is being stored correctly.
In order to do this I added an option in the banners module .xml to allow for a session variable and the name of the session variable. This is being stored correctly in the module table within the params field along with the other module parameters.
Then I started on the
components > banners > com_banners > models > banners.php
by adding two lines of code in getListQuery where the SQL is assembled. They are:
$sess_vars = $this->getState('filter.sess_vars');
$sess_vars_name = $this->getState('filter.sess_vars_name');
But both variables contain nothing even though the ones the component already has can be retrieved fine. Without a doubt I need to change something somewhere else as well - but just can't figure out what to do.
Any help would be greatly appreciated.
The first thing to do is not hack the core files, hacking the core prevents you from using the built-in update feature to apply the regular bug fixes and security patches released by Joomla! (e.g. the recently released 2.5.9 version).
Rather make a copy of them and modify it so it's called something else like com_mybanners. Apart from the folder name and the entry point file (i.e. banners.php becomes mybanners.php) you will also want to update the components banners.xml to mybanners.php.(You will need to duplicate and modify both the front end /components/com_banners/ and /administrator/components/mybanners.php.)
Because of the way Banners work (i.e. banners are displayed in a module) you will also need to duplicate and modify /modules/mod_banners/,/modules/mod_banners/mod_banners.php and /modules/mod_banners/mod_banners.xml. Changing mod_banners to mod_mybanners in each location.
In Joomla! components the state is usually populated when JModel is instantiated, however, in this case the component is really about managing banners and recording clicks the display is handled by mod_banners. So, you will want to add some code to mod_mybanners.php to use the session variables you want to act on. Normally when a models state is queried you will collect the variables via JInput and add them to your object's state e.g.
protected function populateState()
{
$jApp = JFactory::getApplication('site');
// Load state from the request.
$pk = $jApp->input->get('id',0,'INT');
$this->setState('myItem.id', $pk);
$offset = $jApp->input->get('limitstart',0,'INT');
$this->setState('list.offset', $offset);
// Load the parameters.
$params = $app->getParams();
$this->setState('params', $params);
// Get the user permissions
$user = JFactory::getUser();
if ((!$user->authorise('core.edit.state', 'com_mycomponent')) && (!$user->authorise('core.edit', 'com_mycomponent')))
{
$this->setState('filter.published', 1);
$this->setState('filter.archived', 2);
}
}
The populateState() method is called when a state is read by the getState method.
This means you will have to change your copy of /components/com_banners/models/banner.php to capture your variables into the objects state similar to my example above.
From there it's all your own code.
You can find all of this information in the Developing a Model-View-Controller tutorial on the Joomla Doc's site

How to cache data in symfony2

Is there any built in possibility (or an external bundle) to cache data in Symfony2?
I don't want to cache the page itself, but data inside the application, using a simple key -> value store on the file system for example.
There's no built in solution, but I recommend you giving APC, Redis or Memcache a try (they're all in-memory datastores).
You can use LiipDoctrineCacheBundle to integrate cache drivers from Doctrine common into your Symfony project.
i'm using winzouCacheBundle. it gives you a streamlined cache api on different backends (apc,file,memcache,array,xcache, zenddata).
For now, there is no unique solution for caching in Symfony2. Some parts of the framework use Doctrine Common.
There are discussions about a "standard" caching solution if Symfony2, but we will have to wait for some time...
I think the DoctrineCacheBundle is currently the way to go.
The DoctrineCacheBundle allows your Symfony application to use different caching systems through the Doctrine Cache library.
Docs # Symfony.com
Code # Github
If I understand well, you would like to store data (attached to the session) and reload them when the same session will call again a new controller, in order to avoid to execute the same procedure more times (for example to read a table from a database).
You can use the session system in your controllers:
<?php
namespace YourStuff\YourBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class YourController extends Controller
{
$session = $this->get("session");
$variabile = 4;
$session->set("variableName",$variable); // setter
if ($session->has("variableName") // to check if the variable exists
{
$variableName = $session->get("variableName"); // getter
}
}
This is an example; the "variableName" could be accessed next time the same session will be called, if the lifetime of the session is not yet expired.
The "session" uses the __SESSION variable of PHP, so be sure to set correctly the session.cookie_lifetime and session.gc_maxlifetime, in order to give the desired lifetime.

Is it possible to regenerate Code Igniter sessions manually?

As above: Is it possible to regenerate Code Igniter sessions manually? I'm looking for something similar to session_regenerate_id in PHP sessions, so that I could call it manually when a user went through privilege escalation.
Thanks,
Lemiant
CI automatically regenerates the session id every x seconds, which you can set in your config.
You could create a new function in Session.php the same as sess_update() but with the following removed from the top & the function renamed to regenerate_id().
// We only update the session every five minutes by default
if (($this->userdata['last_activity']+$this->sess_time_to_update) >= $this->now)
{
return;
}
This will regenerate the session id, update users_activity and keep the users data. Just call it by $this->session->regenerate_id();
I know this is an old post, but I came across it, so others might too.
You could also do the following so you don't have to hack the core files at all (making codeigniter more easily upgradable with future releases):
//Setting this to 0 forces the sess_update method to regenerate on the next call
$this->session->sess_time_to_update=0;
//Call the sess_update method to actually regenerate the session ID
$this->session->sess_update();
Credit to the original answer for leading me down this path though, thank you.

Resources