DEV Community 👩‍💻👨‍💻

Bogdan Alexandru Militaru
Bogdan Alexandru Militaru

Posted on • Originally published at boobo94.github.io on

Unserialize php in Javascript Nodejs

import PhpUnserialize from 'php-unserialize';

const serialized = 'a:0:{}'
const jsObject = PhpUnserialize.unserialize(serialized);
console.log(jsObject) // {}

Enter fullscreen mode Exit fullscreen mode

NPM Library: https://www.npmjs.com/package/php-unserialize

What happens if your serialized string contains special characters ? yeah, it fails!

In order to solve that we can use

import encoding from 'encoding';

export function convertToUtf8Win1252(str) {
  return encoding.convert(str, 'WINDOWS-1252').toString();
}

Enter fullscreen mode Exit fullscreen mode

So mixing both functions:

export function unserializePhp(str) {
  return PhpUnserialize
    .unserialize(convertToUtf8Win1252(str));
}

Enter fullscreen mode Exit fullscreen mode

NPM Library: https://www.npmjs.com/package/encoding

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.