Skip to content

Instantly share code, notes, and snippets.

@watsonbox
Created April 12, 2012 15:02
Show Gist options
  • Save watsonbox/2367946 to your computer and use it in GitHub Desktop.
Save watsonbox/2367946 to your computer and use it in GitHub Desktop.
PhpSessionStore middleware to allow sharing session with legacy PHP app
# Overrides functionality in Rack::Session::Memcache from Rack 1.4.1 to support sharing PHP sessions
# - PHP side is 5.3.6 configured with session.save_handler = memcache
# - Requires php-serialize gem for serialization: https://github.com/jqr/php-serialize
module ActionDispatch
module Session
class PhpSessionStore < ActionDispatch::Session::MemCacheStore
require 'php_serialize'
def initialize(app, options = {})
require 'memcache'
options[:expire_after] ||= options[:expires]
# Default to no namespace and cookie name matching PHP settings
super(app, options.merge(:namespace => nil, :key => 'PHPSESSID'))
end
def get_session(env, sid)
with_lock(env, [nil, {}]) do
unless session = deserialize_session(sid)
sid, session = generate_sid, {}
unless /^STORED/ =~ @pool.add(sid, PHP.serialize_session(session), 0, true)
raise "Session collision on '#{sid.inspect}'"
end
end
[sid, session]
end
end
def set_session(env, session_id, new_session, options)
expiry = options[:expire_after]
expiry = expiry.nil? ? 0 : expiry + 1
with_lock(env, false) do
@pool.set session_id, PHP.serialize_session(new_session), expiry, true
session_id
end
end
protected
def deserialize_session(session_id)
if session_id
raw_session = @pool.get(session_id, true)
if raw_session && raw_session != ''
PHP.unserialize(raw_session)
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment