Session variable loses index after refresh in Yii - php

I'm having a problem with the session variables in my web app.
The thing is that I set it with the following code and check if it exists and only if not then I update it.
The idea is to know if the user is enterprise or not for his session.
I use the following code:
$logo_class = "logo";
if(!Yii::app()->user->isGuest) {
define("ENT_LIM_PROD_COUNT", 10000);
$user_id = Stores::model()->findByPk(Products::model()->getStoreID())->user_id;
if(array_key_exists('is_enterprise', Yii::app()->session)) {
if(Yii::app()->session['is_enterprise'] === true)
$logo_class = "logo_ent";
} else {
$total_prod = LicenseMngr::getFeatureAllocTotal($user_id, LicenseMngr::FEATURE_PRODUCTS);
Yii::app()->session['is_enterprise'] = ($total_prod > ENT_LIM_PROD_COUNT ? true : false);
if(Yii::app()->session['is_enterprise'] === true)
$logo_class = "logo_ent";
}
}
I have tried using different types of sessions in my config file and now it's:
'session'=>array(
'autoStart' => true,
'sessionName' => 'session',
'timeout' => 30758400
),
Now, the problem is that every time I refresh the page the index "is_enterprise" is not in the session array as if it was never set.
I have tried changing the session save directory to /var/tmp.
I'm running:
Darwin niflheim 12.3.0 Darwin Kernel Version 12.3.0: Sun Jan 6 22:37:10 PST 2013; root:xnu-2050.22.13~1/RELEASE_X86_64 x86_64
PHP Version 5.4.15 (web)
The following line does a rest call to a server to get information we need (It's probably the only thing that isn't related to YII here):
$total_prod = LicenseMngr::getFeatureAllocTotal($user_id, LicenseMngr::FEATURE_PRODUCTS);
P.S: This is not the only custom variable that it happens with, I hope that helps.

OK So after a while we were able to solve the problem... Apparently the session variable in YII is not an array but an object and you can access it as an array so array_key_exists didn't work.
Changing it to isset solved the problem.

Related

Slim3 Twig2 Blank Page - OVH server

I have a blank page when using Slim3 + Twig2 + PHP 7.2 when I run the application on production (OVH server).
I'have been looking for any answer to my problem, but none of what I have found corrected it...
Thanks for your answer.
Here is my code in one of my controller :
function getAccueil($request, $response, $args = array(NULL))
{
if (empty($args))
{
$args['lang'] = 'fr';
}
$lang = $args['lang'];
$fr_url = '/fr.html';
$en_url = '/en.html';
return $this->view->render($response, 'accueil.twig', array(
'lang' => $args['lang'],
'fr_url' => $fr_url,
'en_url' => $en_url,
));
}
I'm using php 7.2 (and already tried with previous versions)
and get a 200 return http code (using Chrome/Devlopment tools/Network)
Try doing killing the script with die(); before returning the twig renderer. If it still gives a blank page maybe check if something is wrong in the php file where you define your $app and $container. Hope that you can do something with this answer.

can't login into my codeigniter app after long time of usage

it's been a while since i've purchased freelancer office on codecanyon. i'm using it since 2015. I've never had an issue till last week. If I type in a wrong password it gives me an error (which is normal :D) however when i type the correct one it just reloads the page :/ i've set the ENVIRONMENT to production but no error messages.. except for deprecated each() call in mx/modules.php file.
Codeigniter version: v3.1.0
php version : 7.1
app url:
http://app.wolftech.eu
i've the same error with another 'app' that ive bought on codecanyon for a friend of mine. after 1 year of succesfull usage it just reloads the page when attempting to login.
Based on the error output that you've provided, I assume that the error comes from codeigniter modular extension hmvc, that show up because it uses each() function that is deprecated.
If you look at one of the official repository pull request, and from this codeigniter forum thread, you could change the third_party/MX/Modules.php files line 83 :
(is_array($module)) ? list($module, $params) = each($module) : $params = NULL;
and replace it to :
if(!is_array($module))
{
$params = NULL;
}
else
{
$keys = array_keys($module);
$params = $module[$keys[0]];
$module = $keys[0];
}

CakePhp sessions clear almost instantly, but only sometimes

I have adopted a CakePhp 2 project. We get to the project from another project, linking to the CakePhp project with a "token" and a conference ID as a parameter in the URL. Using that token, we authorize the user, and using the conference ID get the information from the database. The session value "auth" is set to true.
We have it running on 2 "platforms" locally on my system using a vagrant machine, and on a production server. Locally the session value dies really quick and at random times. On the production server not as often, but the issues we have where Ajax calls don't seem to do what are expected, we believe are being caused by a similar issue. We have many different projects, all Laravel, with zero issues where the session values clear. This issue is strictly with the CakePhp project.
All the authentication magic happens in the beforeFilter method. The code:
public function beforeFilter() {
$session = new CakeSession();
/**
*
* We will check if the current user is authorized here!
*
*/
// If the visitor is coming for the first time, there should be a parameter in
// the URL that is the auth code to check against the database.
if ( ( isset($_GET['conf']) && is_numeric($_GET['conf']) ) && isset($_GET['token']) ) {
$getConference = ClassRegistry::init('Conference')->find('first', ["conditions" => ["conference_id"=>$_GET['conf'] ]]);
$checkToken = ClassRegistry::init('User')->find('first', ["conditions" => ["remember_token"=>$_GET['token'] ]]);
if ($getConference && $checkToken) {
$checkToken['User']['remember_token'] = $this->generateToken();
if ( ClassRegistry::init('User')->save( $checkToken ) ) {
$session->write('auth', true);
$session->write('conferenceId', $_GET['conf']);
$this->redirect('/');
}
}
else {
$session->write('auth', false);
$session->write('conferenceId', null);
}
}
if (! $session->read('auth') || $session->read('conferenceId') == null ) {
echo "No permission!";
exit;
}
}
At the top of the controller:
App::uses('CakeSession', 'Model/Datasource');
When the URL parameters are present, it traps them, does the work, and redirects to the home route without the parameters.
$this->generateToken();
Creates a new token, and overwrites the old one in the database.
There are 2 main controllers. The controller with this code is the main projects controller. The only time it is really hit is the first time you go to the project, and we hit the index method. From there everything else is AJAX calls to the other controller. There is one link, a "home" type link that will hit that index method.
Sometimes these Ajax calls stop working, and clicking that home link will output "No Permission" instead of the expected html in the container the Ajax call outputs too.
Steps to troubleshoot led me to putting this beforeFilter method on the top of the second controller. Now, randomly I'll get no permission. Sometimes, when I'm on the main project that links to this CakePhp project, I click that link, I get no permission right off the bat.
I found this page: cakephp takes me to login page on multiple request and have tried to set the session details like this:
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => '300' // <- added this element
));
And I have tried:
Configure::write('Session.timeout', '300');
Additionally, I have tried cookieTimeout in both of those cases.
I've also tried
Configure::write('Security.level', 'low');
and included
Configure::write('Session.autoRegenerate', true);
In any order, any of these cause the session to bomb out immediately. I get "No permission on page load, and never get anywhere.
The code for this project is honestly crap. The developer who wrote it had mistakes and errors all over the place. On top of that, we are a Laravel shop. We are just trying to keep the project limping along until sometime in the future when we can nuke it from orbit. So we just need to get this working. Any thoughts on what could be causing this? Any other details I am forgetting to include that would help troubleshoot this issue?
Thanks
Reading & writing session data
You can read values from the session using Set::classicExtract() compatible syntax:
CakeSession::read('Config.language');
$key should be the dot separated path you wish to write $value to:
CakeSession::write('Config.language', 'eng');
When you need to delete data from the session, you can use delete:
CakeSession::delete('Config.language');
You should also see the documentation on Sessions and SessionHelper for how to access Session data in the controller and view.

How can I set plain value (no json) for cookie in Yii2

I use this code for set cookie in Yii2:
$cookies = Yii::$app->response->cookies;
$cookies->add(new \yii\web\Cookie([
'name' => 'googtrans',
'value' => '//fa',
'expire' => time()+(60*60*24*365),
]));
When I check cookies manager in browser, I see this:
378abb4ba4b3ed4bd5fa0918a34e0ba6c4042aecd590d167d76f6a901660d082a%3A2%3A%7Bi%3A0%3Bs%3A9%3A%22googtrans%22%3Bi%3A1%3Bs%3A4%3A%22%2F%2Ffa%22%3B%7D
After decode it I see:
378abb4ba4b3ed4bd5fa0918a34e0ba6c4042aecd590d167d76f6a901660d082a:2:{i:0;s:9:"googtrans";i:1;s:4:"//fa";}
Seems, Yii2 convert cookies data to JSON format automatically.
But I don't need this, and I want to have a cookie value plain, with googtrans name and //fa value.
(I know about $_COOKIE in PHP core, but I want use Yii)
How can I do it?
Not JSON. it uses PHP's serialize method before hashing it:
// retrieved from yii\web\Response::sendCookies()
$value = $cookie->value;
if ($cookie->expire != 1 && isset($validationKey)) {
$value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
}
setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
See full code here.
The thing is whenever $enableCookieValidation is set to true (which is the case by default) Yii will do that to validate the received cookies against tamper.
So you may want to completely disable the built-in Cookie Validation by using those configs:
'request' => [
'enableCookieValidation' => false,
'enableCsrfValidation' => false,
]
But I DON'T RECOMMEND IT as there is security reasons to build it that way. To decode the cookie's value anywhere inside the Yii app you can always do it as described in the official docs:
$cookies = Yii::$app->request->cookies;
if (($cookie = $cookies->get('googtrans')) !== null) {
$googtrans = $cookie->value;
}
Otherwise if what you need is client being able to read the real value of some cookie I suggest using $_COOKIE instead to directly set/get it as has been also recommended by its creator here.

PHP Memcached CAS (check and set) issue

Hey all, here are the version of my current setup
Memcached (1.2.2)
Pecl Memcached Client 1.0.2 (using libmemcached 0.43)
Issue: I cant get a cas token returned during a get request
Here is the code in question!
27 public function action_test() {
28 //phpinfo();
29 $m = Model_Mem::getSingleton();
30 $found = $m->get('navigation');
31 echo (int)count($found).'<br />'; // Returns an array of navigation objects
32
33 $cas = 0;
34 $found = $m->get('navigation', null, &$cas);
35 echo (int)count($found); // Returns nothing!
36
37 exit;
38 }
The output from the first echo is 7, and the second echo is 1. Also, the $cas variable as well as the $found variable from the second group of code are both empty. Im not 100% sure if I am doing this right but the cas token just doesnt seem to be working for me at all. Ive went through the php Memcached documentation with no mention on any kind of CAS enable flag that i could easily spot. Ive also tried to look at the memcached.org site for some info but im lost!
Ive never had any problems with it, its just everytime i try and use the cas functionality on a get request i do something wrong. Thanks for anyone helping me out!
*EDIT
Here is what the Model_Mem::getSingleton() function returns
static function getSingleton() {
if (self::$m)
return self::$m;
self::$m = new Memcached();
$servers = array(
array('127.0.0.1', 11211, 25),
array('127.0.0.1', 11212, 25),
array('127.0.0.1', 11213, 25),
array('127.0.0.1', 11214, 25)
);
// Sets up some options for the memcache server
self::$m->setOption(Memcached::OPT_DISTRIBUTION,Memcached::DISTRIBUTION_CONSISTENT);
self::$m->setOption(Memcached::OPT_PREFIX_KEY, Kohana::config('globals.prefix'));
self::$m->addServers($servers);
return self::$m;
}
Arg, debian's latest [secure] memcached release didn't have this feature yet. Upgraded to the latest by installing the memcached server's source and all is well.
Just FYI, CAS means "compare-and-swap": https://en.wikipedia.org/wiki/Compare-and-swap

Categories