응용개발

php에서 serialize/unserialize 사용 시 주의할 점

by 시난 posted Dec 29, 2009
php에서 객체를 문자열로 변환해서 DB에 저장할 때가 있다. 이때 주의할 점..
반환 값이 

Returns a string containing a byte-stream representation of value that can be stored anywhere.
바이트 스트림이기 때문에 일반적인 문자열로 생각할 경우 곤란할 경우가 생긴다.
.

If you are serializing an object with private variables, beware. The serialize() function returns a string with null (x00) characters embedded within it, which you have to escape. Not great if you're trying to save objects into a DB...

위의 글과 마찬가지로 private 변수를 사용할 경우
null(x00) 값이 들어가기 때문에 자칫 c나 php 함수를 사용해서 db에 저장하는 경우 중간에 끊기는 경우가 발생할 수 있다.
(가장 좋은 방법은 blob 같은 데이터 타입을 사용하는 것이다.)

테이블의 컬럼은 VARCHAR 형태로 만든 후
base64_encode()를 사용해서 변경하면 객체를 serialize한 값을 사용할 수 있다.

ex)
 -- 테이블 생성
CREATE TABLE "test_bind"(
    "id" integer AUTO_INCREMENT,
    "var" character varying(1073741823)
);



php 예제
 <?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

$server = "127.0.0.1";
$port = 33000;
$dbName = 'testdb';
$user = 'dba';
$password = 'cubrid';

/*
CREATE TABLE "test_bind"(
    "id" integer AUTO_INCREMENT,
    "var" character varying(1073741823)
);
*/

class ParserOutput
{
    var $mText = 'test';
    private $mIndexPolicy = '';
    private $displayTitle = false;
}


$po = new ParserOutput();
$value = serialize ( $po );
$value = base64_encode( $value );

$con = cubrid_connect($server, $port, $dbName, $user, $password);
if ($con) {
   echo "connected successfully<br/>";
    
   
   $sql = "insert into test_bind(var) values ( ? )";
   $req = cubrid_prepare( $con, $sql );
   
   print "cubrid_bind()";
   $res = cubrid_bind( $req, 1, $value); print " -- OK<br/>";
   
   $res = cubrid_execute( $req );
   print "result: $res <br/>";
   
   if (cubrid_error_code() > 0) {
    print "ERRORCODE:" . cubrid_error_code() . "<br/>";
    print "ERROR:" . cubrid_error_msg() . "<br/>";
   }

   cubrid_commit($con);
   cubrid_disconnect ($con);
}




TAG •

Articles

1 2 3