PHP – Share Session Between Server

PHP – Share Session Between Server

Basically the process is to convert the Session of Server 1, as Cookies. Then in Server 2, we convert back to Session.

Just include below class in both server. Use SessionShare::encode('sessionpass','current_domain'); in Server 1 then redirect to Server 2(use header('Location: http://server2.com')). Then in Server 2, include the same class, decode the Cookies that we created to Session by calling SessionShare::decode('sessionpass');. You should be able to get the same Session values, shared between two servers. 🙂

class SessionShare {
	public static function encode($sessionpass,$domain) {
		
		if(empty($sessionpass) || empty($domain))
			return false;
			
		$op = base64_encode(serialize($_SESSION));
		
		setcookie($sessionpass, $op, false, '/', $domain);
	}
	
	public static function decode($sessionpass) {
		if(empty($sessionpass) || empty($domain))
			return false;
		
		session_start();
		
		$_SESSION = unserialize(base64_decode(@$_COOKIE[$sessionpass]));
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

eleven + 17 =