Cyrus Hackford

PHP

PHP용 커스텀 직렬화 및 역직렬화 클래스: Serializer

by Cyrus H. on Jun.28, 2010, under Made by myself, PHP

방학이 되자마자 정말 잉여로운 삶을 살게 되면서, 내가 생각해도 너무 할 일이 없어 만든 클래스입니다.
PHP가 기본적으로 제공하는 serialize()/unserialize()가 문제점이 있다는 말을 어딘가에서 들은 적이 있기에, 그것을 대체하기 위한 목적으로 만들었습니다1. 주 목적은 PHP 애플리케이션의 환경 설정 등을 데이터베이스에 저장할 때 값을 직렬화하고, 또 역직렬화하는 것입니다. 현재 지원하는 변수형은 다음과 같습니다:

  • array
  • boolean
  • double
  • float
  • integer
  • NULL
  • string
  • object와 reference는 실력이 딸려서 구현을 못 했습니다. :(

다만 주의할 점은, 배열을 직렬화할 때, 키로 NULL을 가진 배열은 직렬화할 수 없습니다. 내부적으로 NULL 키를 가진 녀석을 배열의 끝으로 간주하기 때문입니다. 뭐, 애초에 강제로 array(NULL=>’value’)와 같이 사용하면 PHP가 알아서 array(1) { [""]=>string(5) “value” }로 바꾸긴 하지만요. :D

다음은 예제입니다. 다음 코드를 실행하면, 그 아래의 직렬화된 문자열이 나옵니다.
코드:

<?php

$orgin=array(array(189=>array(3,true),'This is a key!'=>1205,24=>7,42=>'And this is a value!'),'It also performs quote escaping! Like this: Cyrus\' property.','DoubleArray'=>array('PI'=>3.1415926,'e'=>2.7182818));
echo Serializer::serialize($orgin);

?>

결과: (적절히 자름)

array|integer|0:array|integer|189:array|integer|0:integer|3;integer|1:
boolean|true;null|null:null|null;string|'This is a key!':integer|1205;
integer|24:integer|7;integer|42:string|'And this is a value!';null|null:
null|null;integer|1:string|'It also performs quote escaping! Like this: Cyrus\' property.';
string|'DoubleArray':array|string|'PI':double|3.1415926;string|'e':
double|2.7182818;null|null:null|null;null|null:null|null;

이번엔, 위 결과를 그대로 역직렬화 시켜보겠습니다.
코드:

<?php

$orgin=array(array(189=>array(3,true),'This is a key!'=>1205,24=>7,42=>'And this is a value!'),'It also performs quote escaping! Like this: Cyrus\' property.','DoubleArray'=>array('PI'=>3.1415926,'e'=>2.7182818));
//echo Serializer::serialize($orgin);
$serialized=Serializer::serialize($orgin);
var_dump(Serializer::deserialize($serialized));

?>

결과:

array(3) {
	[0]=>
	array(4) {
		[189]=>
		array(2) {
			[0]=>
			int(3)
			[1]=>
			bool(true)
		}
		["This is a key!"]=>
		int(1205)
		[24]=>
		int(7)
		[42]=>
		string(20) "And this is a value!"
	}
	[1]=>
	string(60) "It also performs quote escaping! Like this: Cyrus' property."
	["DoubleArray"]=>
	array(2) {
		["PI"]=>
		float(3.1415926)
		["e"]=>
		float(2.7182818)
	}
}

어떻습니까? 쓸만하잖습니까? 물론, C로 작성된 PHP 내부 함수보단 느리겠지요.

소스 코드 전문을 여기에 붙이려 했으나, 텍스트 래핑 문제가 발생하는 관계로 개인 저장소의 링크를 겁니다. Serializer 클래스의 소스 코드 전문은 여기에 있습니다. GPL v3.

  1. 그런데, 아마 지금쯤이면 해결되었을 겁니다. PHP가 내부적으로 세션 저장에 serialize()/unserialize()를 사용하기 때문에, 문제를 그대로 내버려두면 큰 보안 문제가 생기기 때문이지요. []
Leave a Comment :, , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

나는 세벌식을 씁니다!

Hosted by AQUZ