简体   繁体   中英

PHP Session doesn't work across servers

PHP session variables are not transferring across servers. This is a simple example that I am using to check if it works. Please take a look.

file1.php

<?php
    session_start();

    $_SESSION['FirstName'] = Kshitij ;
    $_SESSION['LastName'] = Kawatra ;
    echo session_id();
    echo "<p>First Name is: " . $_SESSION['FirstName'] . "</p>" ;
    echo "<p>Last Name is: " . $_SESSION['LastName'] . "</p>" ;
?>
<p>Go to the <a href="https://<server-ip>/file2.php">next page</a>.</p>

file2.php(on a different server)

<?php
    session_start();
    echo session_id();
    echo "<p>The FirstName session variable is: " . $_SESSION['FirstName'] . "</p>";
    echo "<p>The LastName session variable is: " . $_SESSION['LastName']. "</p> ";
?>

Even the session id doesn't match.

Sessions don't travel between hosts or servers by default. If you're using cookies to handle sessions the cookies are only sent to the originating server (simplified version). If you move to another host/IP the browser naturally won't send any cookies from another host to that site. If they did everyone could get all your accounts and logins and abuse them.

If you want to transfer sessions between servers you'll have to connect them somehow. If they are completely separate you can for example send a token in the URL to the second server that it can then use to retrieve the necessary information from the first one. The system you'd use depends on what you are actually trying to achieve.

First of all this is not possible with default session behavior http://php.net/manual/en/session.examples.basic.php

You can use another session handler session_set_save_handler or memcached

PHP sessions are local to one server by default. You can't use it on multiple servers directly.

If you want to do so, You'll have to use another session handler.

Refer more details here: How to manage a single PHP5 session on multiple apache servers?

There are ways to communicate between servers, but Session isn't one. PHP Session is actually a memory space with a lifespan of a session refreshed by different possible ways and this memory is server side only and only the server running the PHP code.

The best way, but the hardest one would be to create a socket between these two servers and communicate through layers of security between these two servers.

http://php.net/manual/en/function.socket-create.php

The easiest way would be to create a REST API and communicate through it with JSON output coming from html query string.

Returning JSON from a PHP Script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM