Where is session files stored in Yii2? - php

Where is session files stored in Yii2? I need to know the the exact location. There is options to create a session database.

The default session save path is '/tmp'. link
This path is accessible via the getSavePath() method in the session class file(yii2)
#property string $savePath The current session save path, defaults to '/tmp'.
For example, in xampp software (localhost) go to the following folder(default)
myDrive:\xampp\tmp // The drive where the software is installed
It is taken by default through the session_save_path method. Which depends on the settings of the php.ini file. In session.save_path="...\tmp"
But you can also configure it through the .htaccess file
To adjust Yii2, you can do the following. In the config web file
'components' => [
'session' => [
'name' => '_Session',
'savePath' => dirname(__DIR__) .'/sessions'
],
To save in the database(yii\web\DbSession) refer to this link.
Example:
'session' => [
'class' => 'yii\web\DbSession',
'name' => 'mySession',
// 'db' => 'mydb', // the application component ID of the DB connection. Defaults to 'db'.
// 'sessionTable' => 'my_session', // session table name. Defaults to 'session'.
'timeout' => 30 * 24 * 3600,
'cookieParams' => ['httponly' => true, 'lifetime' => 3600 * 24],
'writeCallback' => function ($session) {
return [
// 'user_id' => Yii::$app->user->id,
// 'last_write' => time(),
];
},
],
writeCallback: To create more data and columns in the database table
Good luck

Yii2 by default stores session files in #app/runtime/data folder.
And if you want to use database instead then yii2 guide is great resource. check this link: https://www.yiiframework.com/doc/guide/2.0/en/runtime-sessions-cookies#custom-session-storage.

Related

Unable to retrieve a cached piece of information that was saved with Laravel app, but trying to get within a phalcon app

I am trying to save a string with one application to memcached. And then after an http redirect, trying to retrieve that information from a different application on the same server. I am able to save, but retrieving the information is not working.
I have made sure that both applications are not applying a prefix to the cache key. I have run 'memcached-tool localhost:11211 dump | less' on the memcache server to ensure the data exists, which it does. I can access the data from the same application that saves the data. So if I save from the Laravel app, I can retrieve from the laravel app, and vice versa for the phalcon app.
The environment variables used are the same in both apps.
Setup in Laravel (cache.php):
'memcached' => [
'driver' => 'memcached',
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 0,
],
],
],
How I am saving in Laravel:
Cache::put($sha, $viewData, 60);
return redirect("someUrl/{$sha}", 302);
Setup in Phalcon:
$di->setShared('memcached', function(){
// Cache data for one hour
$frontCache = new \Phalcon\Cache\Frontend\Data(
[
'lifetime' => 60,
'prefix' => ''
]
);
// Create the component that will cache 'Data' to a 'Memcached' backend
// Memcached connection settings
return new \Phalcon\Cache\Backend\Libmemcached(
$frontCache,
[
'prefix' => '',
'servers' => [
[
'host' => MEMCACHED_SERVER,
'port' => MEMCACHED_PORT,
'weight' => 0,
]
]
]
);
});
How I am trying to retrieve info in Phalcon:
$cache = $this->di->getShared('memcached');
$info = $cache->get($cacheKey);
Here is the output of the $cache var from xdebug:
Phalcon\Cache\Backend\Libmemcached::__set_state(array(
'_frontend' =>
Phalcon\Cache\Frontend\Data::__set_state(array(
'_frontendOptions' =>
array (
'lifetime' => 60,
'prefix' => '',
),
)),
'_options' =>
array (
'prefix' => '',
'servers' =>
array (
0 =>
array (
'host' => 'servername',
'port' => port,
'weight' => 0,
),
),
'statsKey' => '',
),
'_prefix' => '',
'_lastKey' => '38404efbc4fb72ca9cd2963d1e811e95fe76960b',
'_lastLifetime' => NULL,
'_fresh' => false,
'_started' => false,
'_memcache' =>
Memcached::__set_state(array(
)),
))
And here is the dump from memcached-tool:
Dumping memcache contents
add 38404efbc4fb72ca9cd2963d1e811e95fe76960b 4 1562346522 144
a:5:{s:3:"zip";s:0:"";s:10:"first_name";s:5:"Clint";s:9:"last_name";s:9:"Broadhead";s:5:"phone";s:0:"";s:5:"email";s:20:"blah#blah.com";}
I expected to be able to save to memcache from any application and then retrieve that cache from anywhere else that has access to the same server. But when I try to retrieve in the phalcon app I receive 'null'. Even though I can see the key/value pair on the server. Thanks in advance for your assistance.
I bypassed using Phalcons built-in backend and frontend classes and just went with using the PHP ext-memcached on the phalcon app.
$di->setShared('memcached', function(){
if( !($this->_memcache instanceof \Memcached) ){
if( !class_exists('Memcached') ){
throw new CacheException('Unable to connect to cache');
}
$this->_memcache = new \Memcached();
$this->_memcache->addServer(MEMCACHE_SERVER, MEMCACHE_PORT)
return $this->_memcache;
}
});
I started to go down the path of phalcons use of '_PHCM', but once the above solution worked I abandoned that research. Not the best, but works well for my temporary situation.
Phalcon uses prefixes for all cache keys by default. For the Libmemcached adapter
For instance the get for the Libmemcached adapter has:
let prefixedKey = this->_prefix . keyName;
let this->_lastKey = prefixedKey;
let cachedContent = memcache->get(prefixedKey);
https://github.com/phalcon/cphalcon/blob/3.4.x/phalcon/cache/backend/libmemcached.zep#L160
Just make sure that there are no prefixes by setting the prefix option in your options
$di->setShared('memcached', function(){
// Cache data for one hour
$frontCache = new \Phalcon\Cache\Frontend\Data(
[
'lifetime' => 60,
]
);
// Create the component that will cache 'Data' to a 'Memcached' backend
// Memcached connection settings
return new \Phalcon\Cache\Backend\Libmemcached(
$frontCache,
[
'prefix' => '',
'servers' => [
[
'host' => MEMCACHED_SERVER,
'port' => MEMCACHED_PORT,
'weight' => 0,
]
]
]
);
});
https://github.com/phalcon/cphalcon/blob/3.4.x/phalcon/cache/backend.zep#L59
Finally if the above does not work, install a utility that will allow you to query your Memcached instance and see what keys are stored there. Check it before you store data with Laravel and then afterwards. This way you will know whether you check the correct thing or not.
Alternatively you can use good old telnet if you are comfortable with the command line to check the keys.

Need to clear Google OAuth cache?

I set up the Google OAuth with Hybridauth and it works from my development folder e.g. http://example.com/dev and callback is located at http://example.com/dev/callback.php
Now I want to move the dev folder to the production folder e.g. http:/example.com/backend and callback is changed to http://example.com/backend/callback.php
I changed the Authorized redirect URIs from Google console, but Google keeps the old callback link when I do log in.
Is it necessary to clear cache from Google or wait for an amount of time to let Google update the changes?
$config = [ 'callback' => 'example.com/backedn/callback.php',
'providers' => [ 'Google' => [ 'enabled' => true,
'keys' => [ 'id' => 'xxxxx.apps.googleusercontent.com',
'secret' => 'xxxxxxx', ],
'scope' => 'email', ], ], ];
Sorry for my careless mistake as I call the old script from the popup
function auth_popup( provider ){
// replace 'path/to/hybridauth' with the real path to this script
var authWindow = window.open('http://example.com//dev/callback.php?provider='+provider, 'authWindow', 'width=600,height=400,scrollbars=yes');
return false;
}

The "access_key" option must be provided to use fixer.io

For the currency conversion i am using "florianv/laravel-swap": "^1.1" library. Florianv/Laravel-swap.
As Fixer.io has changed its implementation, it is necessary to pass the access_key with the request, and because of that i am getting this error: "InvalidArgumentException: The "access_key" option must be provided to use fixer.io in /var/www/project/project-files/vendor/florianv/exchanger/src/Service/Fixer.php:51".
I registered and got the access_key.
I updated the library using composer and now i can see three constants in the vendor/florianv/exchanger/src/Service/Fixer.php.
const ACCESS_KEY_OPTION = 'access_key';
const LATEST_URL = 'http://data.fixer.io/api/latest?base=%s&access_key=%s';
const HISTORICAL_URL = 'http://data.fixer.io/api/%s?base=%s&access_key=%s';
To pass the access key i tried this:
I have a swap.php in config folder which looks something like this:
return [
'options' => [
'cache_ttl' => 86400, // 24 hours.
'cache_key_prefix' => 'currency_rate'
],
'services' => [
'fixer' => true,
],
'currency_layer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa', // Your app id
'enterprise' => true, // True if your AppId is an enterprise one
],
'cache' => env('CACHE_DRIVER', 'file'),
'http_client' => null,
'request_factory' => null,
'cache_item_pool' => null,
];
This had one more option which was commented, i enabled and passed the access_key in it but it doesn't work.
I also added it in services block below 'fixer => true'.
'currency_layer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa'
]
Also in options block:
'options' => [
'cache_ttl' => 86400, // 24 hours.
'cache_key_prefix' => 'currency_rate',
'access_key'=>'7ca208e9136c5e140d6a14427bf9ed21'
],
I tried with adding access_key in config/services.php file but it also didn't work.
'fixer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa'
],
Even i tried, adding to env file and calling from there, but no success. How do i pass the access_key, can anyone help me on this, what should be the approach.
vendor/florianv/exchanger/src/Service/Fixer.php -> don't touch the constant (that was my own error).
Pass the options-array by creating the Builder:
$options = ['access_key' => 'YourGeneratedAPIKeyAtCurrencyLayer'];
$this->exchangeSwap = (new Builder($options))
->add('fixer', $options )
->build();
I hope I could help ;-)

ZF3 Session empty on each page load

In ZF3, I'm initializing my session as following:
config/autoload/global.php
'session_config' => [
'name' => 'gintra3',
'cookie_lifetime' => 60*60*1,
'gc_maxlifetime' => 60*60*24*30,
],
'session_storage' => [
'type' => Zend\Session\Storage\ArrayStorage::class,
],
'session_manager' => [
'storage' => Zend\Session\Storage\SessionArrayStorage::class,
'validators' => [
Zend\Session\Validator\RemoteAddr::class,
Zend\Session\Validator\HttpUserAgent::class,
],
],
module/Application/Module.php
$sessionManager = $e->getApplication()->getServiceManager()->get(SessionManager::class);
$sessionTableGateway = new TableGateway('session',$e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter'));
$sessionSaveHandler = new DbTableGateway($sessionTableGateway,new DbTableGatewayOptions());
$sessionManager->setSaveHandler($sessionSaveHandler);
Now, when I'm storing data like this on page 1:
$sessionC = new Container('test');
$sessionC->testVariable = "helloWorld";
And retrieve it on page 2 like this:
$sessionC = new Container('test');
Debug::dump($sessionC->testVariable);
I get an output on page 2 like this:
vendor/zendframework/zend-debug/src/Debug.php:97:null
When I check the database table, the 'data' column of the corresponding session_id contains "helloWorld" after loading page 1. After loading page 2, it does not contain "helloWorld" anymore.
If I comment out all session-related lines in Module.php, a PHPSESSID cookie is created on page load and session data saving and storing works fine now.
It does not matter if I use DbTableGateway as a save_handler or just use standard save_handler. The problem occurs in both cases.
When using my individual session storage, also FlashMessenger and Csrf-Form-Validation stop working due to the same mechanism of loosing all session data on page load.
Where is my problem? What am I overseeing?
Thanks a lot for some ideas.

Yii2 Translate Manager doesn't work

I m using a basic template for a small project on Yii2. I have already set the module Language Picker of Lajax (Doc) and I am trying now to manage the translation with the module Translate Manager of Lajax (Github). The plugin is scanning perfectly the project and getting the translatable texts. I even set some translations through this module and everything is saved in the database, but these translations are not set when changing the language.
here are my web.php Configurations:
'language' => 'en-GB',
'components' => [
...
'languagepicker' => [
'class' => 'lajax\languagepicker\Component',
'languages' => ['en-GB', 'fr-FR']
],
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\DbMessageSource',
'db' => 'db',
'sourceLanguage' => 'en-GB',
'sourceMessageTable' => '{{%language_source}}',
'messageTable' => '{{%language_translate}}',
'forceTranslation' => true,
'cachingDuration' => 86400,
'enableCaching' => true,
],
],
],
...
]
'modules' => [
...
'translatemanager' => [
'class' => 'lajax\translatemanager\Module',
'root' => '#app', // The root directory of the project scan.
'scanRootParentDirectory' => false, // Whether scan the defined `root` parent directory, or the folder itself.
// IMPORTANT: for detailed instructions read the chapter about root configuration.
'layout' => 'language', // Name of the used layout. If using own layout use 'null'.
'allowedIPs' => ['127.0.0.1'], // IP addresses from which the translation interface is accessible.
'roles' => ['#'], // For setting access levels to the translating interface.
'tmpDir' => '#runtime', // Writable directory for the client-side temporary language files.
// IMPORTANT: must be identical for all applications (the AssetsManager serves the JavaScript files containing language elements from this directory).
'phpTranslators' => ['::t'], // list of the php function for translating messages.
'jsTranslators' => ['lajax.t'], // list of the js function for translating messages.
'patterns' => ['*.js', '*.php'],// list of file extensions that contain language elements.
'ignoredCategories' => ['yii'], // these categories won't be included in the language database.
'ignoredItems' => ['config'], // these files will not be processed.
'scanTimeLimit' => null, // increase to prevent "Maximum execution time" errors, if null the default max_execution_time will be used
'searchEmptyCommand' => '!', // the search string to enter in the 'Translation' search field to find not yet translated items, set to null to disable this feature
'defaultExportStatus' => 1, // the default selection of languages to export, set to 0 to select all languages by default
'defaultExportFormat' => 'json',// the default format for export, can be 'json' or 'xml'
'tables' => [ // Properties of individual tables
[
'connection' => 'db', // connection identifier
'table' => '{{%language}}', // table name
'columns' => ['name', 'name_ascii'],// names of multilingual fields
'category' => 'database-table-name',// the category is the database table name
]
],
'scanners' => [ // define this if you need to override default scanners (below)
'\lajax\translatemanager\services\scanners\ScannerPhpFunction',
'\lajax\translatemanager\services\scanners\ScannerPhpArray',
'\lajax\translatemanager\services\scanners\ScannerJavaScriptFunction',
'\lajax\translatemanager\services\scanners\ScannerDatabase',
],
],
...
]
I always use something like this im code for translatable strings:
<?= Yii::t('app','Test') ?>
Am I doing something wrong?

Categories