Setting two sessions, a session and cookie [duplicate] - php

This question already has answers here:
Cookies on localhost with explicit domain
(24 answers)
Closed 9 years ago.
I'm trying to set a session and a cookie for when user logs in.
When the user visits the login page, a session is set and started, with session_start() which is working quite alright, but when the user now fills in the login form (with username and password) and the proper check is done for correct login details, I set the cookie:
$one_week = 60*60*24*7;
setcookie("cookiejarcookie", "cookiejar_value", time()+$one_week, '/', 'localhost');
It's not working, the cookie is not being set. I've tried calling it from the top of the script, but it's not working.
How do I set the cookie after setting the session?

Trying to set a cookie on localhost does not work in most browsers. You need to set the domain value to null, empty string or false. Most recommendations I've seen are to set the domain value to false. With that said, I've never understood writing code like that, as it is not something you're going to deploy to a production environment.
See the recommendation by #David. I personally use virtualization to run a server environment and map fake dns using the hosts file.
One tip I can offer is that you have to open your editor (I use notepad++ or wordpad) as administrator on most recent versions of windows that have UAE in order to edit the relevant hosts file.

From my comment
You cannot set cookies to localhost, but if you add a my.fake.local in your hosts file ( /etc/hosts or c:\Windows\System32\drivers\etc\hosts ) that should work.
add
127.0.0.1 my.fake.local
in the appropriate hosts file.

Related

Session PHP expire almost immediately

I've got a problem with my Session in PHP, if I refresh my page it set a new session_id each time.
I use the PHP built in server and PHP 7.1 and nothing more than that :
<?php
session_start();
echo session_id();
Each refresh give me a new Session Id. Each ? Not really in fact, if I refresh super quickly I have the same session id for 1 or 2 seconds.
I don't know where to look, my php.ini seems correct, my code too I believe.
My folder to register session is 777.
Where could I look or what test could I do ?
Edit : I don't know why but changing localhost to 127.0.0.1 in the built in server solved the issue
I don't know why but changing localhost to 127.0.0.1 in the built in server solved the issue.

why cookie delete not working on my server but working fine on my local system?

The cookie is not deleting on my Debian apache server but deleting fine on my local xampp.
Here is the code i used for setting cookie
$token = substr(hash('sha512', mt_rand() . microtime()), 0, 50);
$extime = time()+86500;
$url_parts = parse_url(current_url());
$domain = str_replace('www.', '', $url_parts['host']);
// set cookie
setcookie('rememberme',$token,$extime,"/",$domain);
This code works on the server and rememberme cookie is created on the server.
Here is the code I used for deleting it
// Delete Cookie
setcookie('rememberme',"",0,"/");
The above code work fine on local but not working on my server.
I hosted the test application as subdomain with url like http://example.com/myproject and $domain give value .example.com
If someone knows why it not working properly on server please help me.
As per my comment: (and add the domain as an argument).
setcookie('rememberme',"",0,"/",$domain);
Many a times, it needs the domain.
From the manual on cookies: http://php.net/manual/en/function.setcookie.php and from User Contributed Notes:
"if you are having problems seeing cookies sometimes or deleting cookies sometimes, despite following the advice below, make sure you are setting the cookie with the domain argument. Set it with the dot before the domain as the examples show: ".example.com". I wasn't specifying the domain, and finally realized I was setting the cookie when the browser url had the http://www.example.com and later trying to delete it when the url didn't have the www. ie. http://example.com. This also caused the page to be unable to find the cookie when the www. wasn't in the domain. (When you add the domain argument to the setcookie code that creates the cookie, make sure you also add it to the code that deletes the cookie.)"

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.

Facebook Connect from Localhost, doing some weird stuff

So maybe the documentation is out of date, or I am just off here. But I have done a slew of FB iframe apps (connect), but I am starting my first FB Connect site. Running it from localhost, and the Connect URL is http:// my_external_IP_address. When I click on the FB login button on my site, it pops up, says waiting for facebook, and it returns my site in that box, with the URL up top with the http:// mysite/?session={session key, user_id, etc.} The user_id is infact my FB id. And so it thinks I am logged in. If I close the popup, I'm not logged in. I'm not sure why the pop up isn't doing the normal fb connect dialog. I'm following these steps.
(I added spaces to the http:// as to not be detected as 'spam')
html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"
right after <body> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript">
At the end, before the body close tag: script type="text/javascript">
FB.init("fbkey", "http://127.0.0.1/xd_receiver.htm");
I have tried using xd_receiver.htm, /xd_receiver.htm (and other combos), and that brings up a blank page. using the http://127.0.0.1 at least does something.
In my config file, which is called before all of those, it checks for a PHP session key
to see if they are logged in, if that doesn't exist it looks for a cookie, and if that doesn't exist it does this:
require_once('includes/facebook.php');
$facebook = new Facebook($fbkey, $fbsec);
$user_id = $facebook->get_loggedin_user();
if($user_id > 0){
$user = $ac->getUserFromFB($user_id);
$_SESSION['user_id'] = $user['user_id'];
}
The user_id is always empty when I echo it out to the screen to test. The session event never occurs as well. So I don't know what it is doing in the popup, but I think Facebook thinks it is logging me in. Not sure. Pretty stumped on this one. Any help would be appreciated. Thanks!
I've personally found the easiest way to deal with facebook connect is to use winscp to sync my localhost to a server with a domain somewhere. Since fb connect is attached to an application, that application needs to be bound to a domain, which is where the api key gets generated. Somewhere in there, your localhost isnt working, unsurprisingly.
I don't know for sure but I suspect the problem is due to you running on your local machine.
My guess is that the Facebook server won't be able to find your machine on 127.0.0.1 as that is a local ip address. You could try using somewhere like whatisyourip.com to get your actual remote ip and use that instead but even then you would need to make sure that you have the necessary port forwarding set up for the FB server to be able to get to your local machine.
All in all, for this kind of site I think it would be easier to develop on an external server rather than a local environment.
Incidentally, I don't have to enter the second parameter for FB.init() - I just use
FB.init(fbkey);
If you haven't already, you could try taking that out completely to see if it helps.
Also I think that the script tag to include the facebook FeatureLoader.js should be before your </head> tag not after the <body> tag
Try editing your hosts file to point a hostname (doesn't matter what it is, as long as you set it as the hostname associated with your app in the settings) to 127.0.0.1, and then restarting your browser and visiting your local app via the domain you set in the hosts file. This should allow you to test most FB-related features. The main exception will be the Like button, because it depends on Facebook's servers also being able to access your app at the domain in question.
Example hosts line:
127.0.0.1 www.example.com
If you add the above you your /etc/hosts and restart your browser, you can replace the "127.0.0.1" component of the URL you're testing with www.example.com and it will be as if the domain associated with your app were indeed www.example.com

Categories