PHP cookies in a multi-server environment - php

I am experiencing difficulties retrieving a cookie in an environment where the URL is http//somesite.com and the request is sent through a load balancing application and farmed out to various servers. I can set the cookie using setcookie in a PHP script as follows:
setcookie("NameTest", $cookieText, time()+3600, "/");
and a cookie somesite.com is created however when I attempt to read the values back from that cookie on the running system I never find the created cookie. I know there must be a way of doing this but haven’t found anything I can use. Can anyone tell me how to accomplish this function?
This of course works perfectly on a single server without the load balancing routine

Cookies are round-tripped client<->server on every request. If the cookie's not present on subsequent requests, you'll have to figure out why the client isn't sending it. If the load balancer is transparent to the end user, then it shouldn't matter which server is handling the request - the client would've send the cookie regardless. So if it's not being sent, then it's not being set properly in the first place.

Yes you can, because externally the client sees same IP and domain address. But if you need to share SESSION info, you have to use something like memcached or mysql to share session data between nodes.

Related

PHP maintain Session ID Between Multiple Servers Memcached

I need to share PHP sessions between multiple servers. However, I'm not sure how to maintain the session ID created on one server and how to pass it to the next server.
Essentially, a client can upload a file, but which server the file is sent to depends on which server is not overloaded.
For example, session_start() is called on test.com
An AJAX post is sent to serv1.test.com. When I call session_start() on serv1.test.com, I want it to pull the existing session information that was created by session_start() on test.com. However, that doesn't seem to be the way PHP sessions work?
I installed Memcached and followed this guide here:
https://www.digitalocean.com/community/tutorials/how-to-share-php-sessions-on-multiple-memcached-servers-on-ubuntu-14-04
I have one centralized memcache server that test.com and serv1.test.com are configured to use. However, session_start() creates a unique session on each server instead of reusing the same session. If I send the PHPSESSIONID to each server, then I can load the existing session.
How do I accomplish what I'm trying to do? I could send the PHPSESSIONID as a variable in the AJAX POST, but isn't that a security risk? That is something that could be changed by the user...
How do I get serv1.test.com to continue to use the same session set on test.com? How do I pass that session ID to serv1.test.com securely so I can use session_id("existingsessionid_from_test.com") to open the existing session?
The solution was to set the session.cookie_domain to include subdomains.
session.cookie_domain = ".test.com"
Thanks frz3993

Who creates a session and how does cookie and any role in it?

Who creates a session and how does cookie and any role in it?
I was asked this question in a company's interview process and didn't know the answer. I would like to to know which side creates Sessions i.e whether the client side or server side and does cookie has any role in it.
Also how the server understands which session is provided to which client and which user of client if multiple users are logged in?
What’s the difference between a cookie and a session in PHP?
PHP sessions improve upon cookies because they allow web applications to store and retrieve more information than cookies. PHP sessions actually use cookies, but they add more functionality and security.
Sessions store data on the server, not on the browser like cookies
The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser. Sessions use a session identifier to locate a particular user’s session data. This session identifier is normally stored in the user’s web browser in a cookie, but the sensitive data that needs to be more secure — like the user’s ID, name, etc. — will always stay on the server.
Sessions are more secure than cookies
So, why exactly should we use sessions when cookies work just fine? Well, as we already mentioned, sessions are more secure because the relevant information is stored on the server and not sent back and forth between the client and server. The second reason is that some users either turn off cookies or reject them. In that scenario, sessions, while designed to work with a cookie, can actually work without cookies as a workaround, as you can read about here: Can PHP sessions work without cookies?.
Sessions need extra space, unlike cookies
PHP sessions, unlike cookies which are just stored on the user’s browser, need a temporary directory on the server where PHP can store the session data. For servers running Unix this isn’t a problem at all, because the /tmp directory is meant to be used for things like this. But, if your server is running Windows and a version of PHP earlier than 4.3.6, then the server will need to be configured – here is what to do: Create a new folder on your Windows server – you can call it something like C:\temp. You want to be sure that every user can read and write to this folder. Then, you will need to edit your php.ini file, and set the value of session.save_path to point to the folder which you created on the Windows server (in this case, that folder is under C:\temp). And finally, you will need to restart your web server so that the changes in the php.ini file take effect.
Sessions must use the session_start function
A very important thing to remember when using sessions is that each page that will use a session must begin by calling the session_start() function. The session_start() function tells PHP to either start a brand new session or access an existing one.
How session_start in PHP uses cookies
The first time the session_start() function is used, it will try to send a cookie with a name of PHPSESSID and a value of something that looks like a30f8670baa8e10a44c878df89a2044b – which is the session identifier that contains 32 hexadecimal letters. Because cookies must be sent before any data is sent to the browser, this also means that session_start must be called before any data is sent to the Web browser.
link-1
link-2
link-3
link-4
The server creates the session and sets the cookie, which is stored in the client's browser. The cookie contains a session identifier (a string of characters) that allows the user to access a particular session on the server. This session identifier corresponds to the session on file.

php cookies on load balanced web servers

I have setup a simple user login session as below in the pages of my web app:
if (!isset($_SESSION['username'])){
if (isset($_COOKIE['username'])){
$_SESSION['username'] = $_COOKIE['username'];
}
I started to notice that on some occasions I would loose my login session. I checked the cookie expiry time and that was definitely set for a future date. The behaviour was quite random where sometimes replicating the action would not cause the issue.
Today I discovered that the web servers (x2) are load balanced (clumsy of me to not have picked up on this) and now I suspect the issue spits up when a user sends a request to the 2nd web server where a cookie doesn't exist.
I would have thought when you hit a web server it would maintain a session with it. However the behaviour suggests otherwise.
I have not spoken to the web admin yet. Is there a magic solution the web admin can sort me out with? or is this an implementation problem? If so, any ideas on how I can solve this?
Suggestions are much appreciated.
The cookie doesnt care what backend server handles the request, unless the url changes. If the url changes from www1.xxx.xx to www2.xxx.xx then you could save the cookies with the path included (xxx.xx) and both subdomains will be able to see the cookie.
Another thing that is more likely to go wrong is that the sessions arent shared between both servers. You could use memcached for this.

PHP file_get_contents server check

I have separate servers for my projects, and I would like to ask for stuff across all of them. I found that I had to use either PHP: file_get_contents or cURL, but then here is my question. Is there a way for my servers to verify which server can ask them execute stuff?
For example I use this script:
function is_ajax() {
// BOOLEAN return if AJAX
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
to check wether or not the request is AJAX based.
I will probably have access to each servers IP address, if there is a way to use those.
I can tell that one of the things I want to execute is starting a session on SERVER B, after SERVER A has verified some informations. So to prevent other servers and scripts to execute without permission I want a way for my SERVER B to verify that it actually is SERVER A who's asking.
EDIT:
I am creating a session on SERVER A using a session class that saves the data encrypted in an SQL database.
Also by using session cookie parameters
session_set_cookie_params(
$cookieParams['lifetime'],
$cookieParams['path'],
$cookieParams['domain'],
$secure,
$httponly
);
And even though the servers are different, they share same domain name but are separated in sub domains across the servers, so maybe a way would be to let SERVER B see the session at SERVER A and then create a similar session?
If you have sessions stored in a centralized data store like memcached, then your servers would share the same sessions if they are accessed from the same domain. PHP supports storing sessions in memcached, so you just need to configure it (session.save_handler) to do so. Then all your session code would still work as is, but your sessions would be shared across servers.
I settle with the ?SOMEPASSWORDVARIABLE=LONGSPASSWORDWITHRANDOMCHARS
as #complex857 suggested.
as file_get_contents is run server side, it's not very easy to guess the file name file
the variable and the password, if the actual request could be monitored by monitoring your traffic from your server but the likelihood is very small
Use a [crossdomain.xml][1] file to specify which domains are able to make requests. Requests from other domains will be denied.

PHP session resets when switching through tabs on the same domain

I have a website (www.mysite.com) with a private backend (www.mysite.com/admin)
When I'm adding content to the site in the admin area and switch back and forth between tabs in the same browser window to see the content I'm editing, my session is getting expired/ended/terminated and I'm redirected to the login page again.
I have used the same code many-many times before on many web sites (this is a CMS I've made by myself) without a problem. The only thing I can think of is that this particular website is hosted on a different web server and maybe it's a matter of a php.ini setting or server configuration. Any ideas?
Have you checked your browser cookies? (the actual client-side ones?) or tried your luck with another browser? It may sound a bit strange, but I had a similar problem and in my case it had to do with these cookies. It may be worth figuring out because of your odd problem. As you might know the phpsession value is stored in that cookie and so is the domain.
Good luck!
This could be a result of several things, but my first instinct is to check and see if the session cookies are expiring very quickly. Sometimes server headers may change expiry values. You may also want to check the cache headers being sent by the server. If you are using asynchronous functionality on the admin area, it is possible that somehow the server is changing the expiry of cached files which could affect this.
I am eager to see the solution to this.
A few things to check:
session.cookie_lifetime setting - Possibly too short; 0 is the default and keeps the cookie until the browser closes
session.cookie_path setting - You'll want this to be '/'
Session storage - Make sure the session data is being written.
Explicitly call session_close() if your sessions are stored in a database. That will ensure they are written before your objects and database resources are destroyed.
If serving through any sort of proxy, check for any changed header information.
If caching, check your dynamic pages (requiring sessions) are being served by your web app and not the cache.
If testing with your local /etc/hosts, first clear your cookies so the new server's cookies are fresh and don't conflict.
Confirm in your browser that the cookie is in fact being stored. Maybe it's not actually coming back in the header.
I had a problem like this before. I was just uploaded a site from my localhost to a remote host, and I haven't change the nameservers yet. The hosting company provided me with a temporary url to be able to see my website. The problem was that this url was like this https://server_name.grserver.gr:8443/sitepreview/http/my_site.gr/, the result was that any browser didn't accepted the session cookie because I didn't had an SSL sertificate so the sessions didn't worked at all. I browsed a little the plesk panel and I found an other temporary url that was using http protocol, with this everything was ok. So if you are using https try to check if you have a problem with your ssl sertificate (for expample if it has expired). You said the problem occurs when you login in the admin page, do you switch then to https?
There could be several reasons. As there is no code or no details about the site provided , I am assuming that the problem might be if you are using htpasswd. If u are using htaccess authentication, then your session gets destroyed.
From experience, I can tell you a few things.
First, sessions need to be started with
session_start();
At the top of every page you want to use sessions.
Next, to save session data, you need to call another function to tell php that you are saving stored data. That function is
Session_write_close();
That function is needed on the bottom of the page when you are finished writing data to a session and want it saved for later use.
With those two combined, that should allow you to properly write to a session, save the data you entered into it, and access it later on your site.
Good luck.
The problem has been found after reading this topic.
I had a custom php.ini in the root dir and apparently it was interfering with the $_SESSION. I don't know why but after deleting it everything works fine.
At first it seemed as if the problem was opening pages located in different sub-folders in several browser tabs however it narrows down to a sub-folders issue and the fact that the $_SESSION wasn't accessible across them.
I'd like to thank everyone that put some time into trying to help me figure this out.

Categories