Skip to content

Instantly share code, notes, and snippets.

@scragg0x
Created October 15, 2012 19:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save scragg0x/3894835 to your computer and use it in GitHub Desktop.
Save scragg0x/3894835 to your computer and use it in GitHub Desktop.
Unserialize PHP Session in Python
def unserialize_session(val):
if not val:
return
session = {}
groups = re.split("([a-zA-Z0-9_]+)\|", val)
if len(groups) > 2:
groups = groups[1:]
groups = map(None, *([iter(groups)] * 2))
for i in range(len(groups)):
session[groups[i][0]] = phpserialize.loads(groups[i][1])
return session
@listm
Copy link

listm commented Jul 30, 2014

Works using python3:

def unserialize_session(val):
    def f(*x): return x
    if not val:
        return
    session = {}
    groups = re.split(b"([a-zA-Z0-9_]+)\|", val)
    if len(groups) > 2:
        groups = groups[1:]
        groups = map(f, *([iter(groups)] * 2))

        for x in groups:
            session[x[0]] = phpserialize.loads(x[1]) #if you want to access the values using strings you need to use session[x[0].decode('ascii')] = ...
    return session

@ivan-klass
Copy link

Why not just use zip?

       groups = zip(*([iter(groups)] * 2))

    for key, php_value in groups:
        session[key] = phpserialize.loads(php_value)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment