How to continue a CakePHP 3 session in a regular PHP script? - php

My situation is the following. I have a cakephp project and a seperated plain php script running on the same server.
When I use my client browser to connect to the cakephp project, it builds up a session as it should.
Now I want to continue the session data with my plain php script. Again I use the same client browser to access the plain php script (so the request meta data should be the same and the session should be recognized) and I set cakephp session option to PHP.
'Session' => [
'defaults' => 'php',
],
However, I cant find out how to continue the session on the plain php script.
I would have assumed the following two lines of my plain php script would do the magic:
session_start();
echo json_encode($_SESSION);
Kind regards,
Marius

CakePHPs PHP session defaults (like all built-in defaults) do change the name of the cookie / the name of the session (session.name INI setting) to CAKEPHP:
https://github.com/cakephp/cakephp/blob/3.5.3/src/Network/Session.php#L133-L138
So you either have to change that to match the defaults used by your vanilla PHP app (which is most probably PHPSESSID, ie the PHP default):
'Session' => [
'defaults' => 'php',
'cookie' => session_name(), // would use the PHP default
],
// ...
or change the latter app to use the name configured for your CakePHP application:
session_name('CAKEPHP');
session_start();
// ...
Also make sure that the session.cookie_path and session.cookie_domain configuration covers both of your applications locations.
See also
Cookbook > Sessions > Session Configuration
Cookbook > Sessions > Setting ini directives

Related

Rename PHP session cookie with __Secure-/__Host- prefix

I'm trying to rename my PHP session cookie from PHPSESSID to __Secure-PHPSESSID as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#Examples.
Since PHP does not offer this mechanism, I am doing it through Apache server configuration:
RequestHeader edit Cookie ^__Secure-PHPSESSID(.*)$ PHPSESSID$1
Header edit Set-Cookie ^PHPSESSID(.*)$ __Secure-PHPSESSID$1
Header edit Set-Cookie ^(.*)(?<!SameSite=Strict)(?<!SameSite=Lax)$ "$1;SameSite=Lax"
This works correctly in Firefox, Edge, and Safari, but not Chrome. On Chrome, I can see that the cookie is set with the correct name and flags but I cannot log in to my site.
Upon login, the output of var_dump($_SESSION['internal']['user_name']) is NULL on Chrome but shows the correct username on Firefox and other browsers. I can also see that the session ID is being regenerated every time I try to log in and the value is set in the __Secure-PHPSESSID cookie.
I tried removing the SameSite flag (line 3 above) and it still does not work.
Any ideas?
PHP does indeed offer this mechanism. You can change it in php.ini. Just set this and restart the site:
session.name = __SECURE-PHPSESSID
To confirm it's right, restart your browser to clear previous session cookies.
As for Chrome not letting you log in, this page may give you some clues (see "Option Secure" and "Prefixes" sections): https://www.mon-code.net/post/108/Secure-cookie-of-you-web-application-with-PHP-or-Symfony
They are not well known, but supported by all browsers except those of
Microsoft. With prefixes, it's possible to force the browser to not
accept a cookie if it's misconfigured. There are two prefixes
"__Secure-" and "__Host-".
__Secure- forces the developer to add the secure flag to his cookie, otherwise it will be ignored by the browser.
setcookie('__Secure-user_id', 10, 0, '/', 'orion.dev', true);
__Host- is more restrictive, cookie must have the secure flag but also path to root and blank domain.
setcookie('__Host-user_id', 10, 0, '/', '', true);
I'm not familiar with Cookie Prefixes but PHP should support it out of the box:
<?php
session_name('__Secure-PHPSESSID');
session_start();
You can actually achieve it using PHP, changing session.name parameter. You can do it:
using session_name() in your PHP script
in .htaccess file
directly into CPanel table that shows PHP options (if you run CPanel)
Examples:
// Example way 1
session_name('Secure-PHPSESSID');
session_start();
// Example way 2
php_value session.name "Secure-PHPSESSID"

Yii 1 CDbHttpSession timeout ignored

Both CDbHttpSession and CHttpSession seem to be ignoring the timeout value and garbage collect data after a fairly short time (less than 12 hours). What could be the problem?
'session' => array(
'class'=> 'CDbHttpSession',
'autoCreateSessionTable' => true,
'autoStart'=>true,
'timeout' => 1209600,
'cookieMode' => 'only',
'sessionName' => 'ssession',
),
May be this is what you are looking for
Setting the timeout for CHttpSession just sets the
session.gc_maxlifetime PHP setting. If you run your application or
Debian or Ubuntu, their default PHP has the garbage collector disabled
and runs a cron job to clean it up.
In my apps I set the session dir somewhere in protected/runtime to
separate my session from other apps. This is important on shared
hosting sites and it's a good habbit. The downside is that I have to
remember to set up a cronjob to clean the files in that folder.
Anyway, you should also set a timeout when calling CWebUser.login to
log in a user.
from Yii Forum Post
Check duration parameter in CWebUser.login

Can't access Session variables on different servers

I have dedicated a server to maintain Memcached and store sessions, so that all my servers can work on the same session without difficulties.
But somehow I think I may have misunderstood the meaning of Memcached possibilities about PHP sessions.
I thought that I would be able to stand on Apache 1 a.domain.com and create a session e.g. $_SESSION['test'] = "This string is saved in the session" and then go to Apache 2 b.domain.com or c.domain.com and simply continue the session and type echo $_SESSION['test']; and it would output the string.
It doesn't, but i am sure that I was told that memcached would be a great tool if you have multiple webservers to share the same session.
What have I done wrong?
By the way. We seriously need a fully detailed tutorial or ebook to describe how to set up the server, using php, building clusters etc. based on Memcached.
In my php.ini file it says:
session.save_path = "192.168.100.228:11211"
Tutorials told me not to define a protocol, and the ip address has been given to the Apache 3 - memcached Server
Here is an image of phpinfo()
The domain in session.cookie_domain is not called domain but it is a .local.
It has been changed for this image.
EDIT:
Just for information. When I am using a simple Memcached based PHP command - everything works perfectly. But somehow when I am trying to save a session, the memcached server doesn't store the item.
This works:
<?php
$m = new Memcached();
$m->addServer('192.168.100.228', 11211);
$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));
/* expire 'object' key in 5 minutes */
$m->set('object', new stdclass, time() + 300);
var_dump($m->get('int'));
var_dump($m->get('string'));
var_dump($m->get('array'));
var_dump($m->get('object'));
?>
This doesn't work
<?php
session_start();
$_SESSION['name'] = "This is a simple string.";
?>
EDIT 2: THE SOLUTION
I noticed that after deleting the cache history including cookies etc. the browser didn't finish the job. The problem continued due to the fact, that it hang on to the original individual session id, which made each subdomain separated from each other.
Everything defined here is correct, just make sure your browser resets its cookies when you ask it to. >.<
By default (session) cookies are domain specific, so set the cookie domain in your php.ini
session.cookie_domain = ".domain.com"
Also see here
Allow php sessions to carry over to subdomains
Make sure to restart your webserver and clear all of your browser cookies after making the change. Your browser could get confused if you have cookies with the same name but different subdomains.
Other things to check:
That the sessions work fine on each individual server.
Make sure the session handler is set properly by using phpinfo() if you are working with a large codebase especially inherited / 3rd party stuff there may be something overriding it.
If you are using 3rd party code - like phpbb for instance - check that the cookie settings are correct in there too.
(please note this answer tidied to remove brainstorming, kept all relevant info)

Why I can not login to magento backend using google chrome

I am using magento community edition 1.7.0.2.I am not able to login to back end of magento.I know this problem can be because of chrome not accepting cookies.
But how to fix that please help.
Thanks
If you enabled the https for the Magento admin panel, then make sure to set "NO" for the option "Use HTTP Only" under System->configuration->web->Session and Cookie Management."
If you have access to the database then open the table "core_config_data" and search for the Path "web/cookie/cookie_httponly" and set the value to "0".
Make sure to delete the var/cache folder. Now try to login to Magento admin panel. Mostly you can now. If not post your issue in this thread.
So this "Not able to login Magento admin panel" issue mostly relates to the Magento cookies settings. So don't get worried if you encounter this tiny issue. With the list of answers in this thread you can easily sort this out in a few minutes time.
There are two solutions for this, either one will work:
Change the cookie lifetime configuration.Go to backend -> Sytem -> Configuration -> Web -> Session and Cookie Management
Set cookie lifetime to 86400 and save it .
Go to app/code/core/Mage/Core/Model/Session/Abstract/Varien.php file within your magento directory.
Find the code:
session_set_cookie_params(
$this->getCookie()->getLifetime(),
$this->getCookie()->getPath(),
$this->getCookie()->getDomain(),
$this->getCookie()->isSecure(),
$this->getCookie()->getHttponly()
);
or
// session cookie params
$cookieParams = array(
'lifetime' => $cookie->getLifetime(),
'path' => $cookie->getPath(),
'domain' => $cookie->getConfigDomain(),
'secure' => $cookie->isSecure(),
'httponly' => $cookie->getHttponly()
);
and replace with
session_set_cookie_params(
$this->getCookie()->getLifetime(),
$this->getCookie()->getPath()
//$this->getCookie()->getDomain(),
//$this->getCookie()->isSecure(),
//$this->getCookie()->getHttponly()
);
or
// session cookie params
$cookieParams = array(
'lifetime' => $cookie->getLifetime(),
'path' => $cookie->getPath()
// 'domain' => $cookie->getConfigDomain(),
// 'secure' => $cookie->isSecure(),
// 'httponly' => $cookie->getHttponly()
);
After this save the file.
This so far is the best solution rather than changing the code elsewhere http://iamtheshadowonthesun.blogspot.com/2012/10/magento-cannot-login-to-admin-panel.html
Using phpMyAdmin, in your magento database, look for the core_config_data table and click it. Click the "Search" tab. Then on the "path" column set the operator to LIKE %...% and the Value to cookie and click the "Go" button to search.
After searching, set the value of web/cookie/cookie_path, web/cookie/cookie_domain, web/cookie/cookie_httponly, and web/browser_capabilities/cookies to NULL
what worked for me is what Haijerome, unfortunatelly I can't login into the backend to change the config.
This is what I execute whenever I install a new fresh magento:
insert into core_config_data(scope, scope_id, path, value) values("default", "0", "web/cookie/cookie_httponly", "0");
then:
rm -Rf var/cache/mage--*
One simple solution is to do the installation using Opera browser and use it to log in because it saves the cookies itself. It works!
Our Chrome users were unable to add items to their cart... changing the Cookie Lifetime to the recommended 86400 fixed it.
Magento Community 1.7
Thank you!
Jeff
the problem is that chrome isnt storing the login cookie, this can be seen by looking at the cookies in chrome | settings | content | advanced | all cookies and site data
there's probably a number of reasons why this can happen, cookie lifetime for sure is one of them..
personally I encountered this problem when running magento in localhost / on a virtual machine and connecting from a browser on the same machine. specifically the problem seems to be that chrome will not store cookies if the domain name is not qualified. so if your domain name is 'http://localhost/magento' or 'http://somename/magento' chrome will not store the cookie and consequently you will not be able to login
here's the fix:
to keep this simple i'm sticking to the example where magento is running on localhost. the same trick will work if magento is running on a vm and you're accessing from localhost, but you need to modify the hosts file on both guest os and client in such a case. (and remember that the guest ip can change so from time to time you need to update the hosts file on the host)
first choose your domainname. it's only in local so you dont need to register. i'm choosing 'dansmagentodev.com'. then in magento | system | web modify baseurl in both secure and unsecure to be
http://dansmagentodev.com/magento/
next, in the same place, modify the session cookie management 'cookie domain' to be 'dansmagentodev.com'
next we need to configure your system to know that dansmagentodev.com is really localhost. we do this via the hosts file. on windows this file is in C:\Windows\System32\drivers\etc\hosts. your virus checker will probably try to stop you modifying it (for good reason, disable virus checker while you make the modification). then add the line
127.0.0.1 dansmagentodev.com
And now log in from chrome.
My problem was the fact that the server I was running was an Ubuntu fresh install with very little server maintenance configuration.
It had not updated it's date & time and it was 3h behind.
This made cookies received by Chrome to look as if they were already expired so Chrome discarded them.
If on firefox works. Then the problem is cookies on chrome, try to clear your chrome's cookie.

Auth timeout problems with CakePHP

This is really bugging me. Has been for years. No matter what I do with core.php or php.ini, my logins timeout after about an hour - usually. Some deployments of identical code and configuration timeout after a respectable amount of time.
This is what I have at the moment on one site - timed out after about an hour:
session.gc_divisor 1000
session.gc_maxlifetime 86400
session.gc_probability 1
Configure::write('Session.timeout', '28800');
Configure::write('Session.checkAgent', false);
Configure::write('Security.level', 'medium');
And another - lasted all night:
session.gc_divisor 100
session.gc_maxlifetime 14400
session.gc_probability 0
Configure::write('Session.timeout', '315360000');
Configure::write('Session.checkAgent', false);
Configure::write('Security.level', 'medium');
Now, before you get excited and say, "Well, the answer is there in the Session.timeout value", let me tell you that this site usually times out after about twenty minutes!
Somewhere I read that on shared hosting, other applications can reset the session by clearing the php-defined session directory. This was alluded to by Rowlf in his answer.
CakePHP offers the option to configure the way sessions are handled. In core.php I changed this to 'cake' (by default it is 'php'):
/**
* The preferred session handling method. Valid values:
*
* 'php' Uses settings defined in your php.ini.
* 'cake' Saves session files in CakePHP's /tmp directory.
* 'database' Uses CakePHP's database sessions.
*/
Configure::write('Session.save', 'cake');
I also ensured that the session timeout and the corresponding php.ini values are the same:
/**
* Session time out time (in seconds).
* Actual value depends on 'Security.level' setting.
*/
Configure::write('Session.timeout', '86400');
So far, the system hasn't logged out.
I don't think this is a Cake-specific thing; I've seen it when no frameworks were involved - it's most likely an issue with your PHP config settings.
Things you should check/do to fix the issue:
Specify a dedicated path to store
sessions in session.save_path if you don't already do so.
Don't store them in /tmp - some other process may come along and wipe them
for you.
Make sure (and I mean really sure) that the value of session.gc_maxlifetime is what you think it is (86400 if you want your logins to time out after 24 hrs of inactivity, etc.). Same with session.gc_divisor and session.gc_probability. Even though the PHP Manual specifies that session settings can be set on any level, depending on the dodginess of your PHP build (they're all slightly buggy in their subtle ways :)) you may find they don't actually take effect unless set in the global php.ini file as opposed to in the code, .htaccess, etc. Just output them in your actual app to be sure they are applied.
Also, depending on your environment, check if the PHP CLI build is using the same php.ini file as the default PHP build - if the CLI build is using another config file and you have cron jobs using the CLI build, the cron job scripts could be invoking the session cleanup procedure.
If you have many CakePHP apps on the same server, this can be the cause of you troubles. Don't forget to :
Prefix each app differently ($prefix on core.php).
Change the name of each cookie path :
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => 4320,
'ini' => array(
'session.cookie_path' => '/name_app', // this for each app
)));

Categories