DB
PHP
LLM

S&P 500

SPI@SPX 미국 2026.01.07 16:54 현지시간 기준 |10분 지연제공

6,920.93

전일대비 23.89 ( -0.34% )

나스닥 종합

NAS@IXIC 미국 2026.01.07 16:15 현지시간 기준 |15분 지연제공

23,584.28

전일대비 37.11 (+ 0.16% )

다우 산업

DJI@DJI 미국 2026.01.07 16:20 현지시간 기준 |15분 지연제공

48,996.08

전일대비 466.00 ( -0.94% )

세션(Session) 핸들러::PHP

작성자아이디 : skok1025, 2022-09-19 21:41:24
카테고리 : Language PHP 게시글 수정

데이터베이스를 이용한 session 처리 핸들러 예제입니다. (* SessionHandlerInterface 인터페이스 구현체,)

아래와 같이 open, close, read, write. destroy, gc 를 구현하면 DB 를 통해서도 세션관리가 가능합니다.

(일반적으로는 프레임워크에서 세션처리 구현이 되어있기 때문에 아래와 같이 작업할 일이 없음)


테이블

    CREATE TABLE sessions(
        id VARCHAR(255) UNIQUE NOT NULL,
        payload TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        update_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )



소스

<?php

date_default_timezone_set('Asia/Seoul');

/**
* Session Handler Interface
*/
class DatabaseSessionHandler implements SessionHandlerInterface
{
private PDO $pdo;

public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}

public function open($path, $name)
{
return true;
}

public function read($id)
{
$sth = $this->pdo->prepare('SELECT * FROM sessions WHERE `id` = :id');

if ($sth->execute([':id' => $id])) {
if ($sth->rowCount()>0) {
$payload = $sth->fetchObject()->payload();
} else {
$sth = $this->pdo->prepare('INSERT INTO sessions(`id`) VALUES(:id)');
$sth->execute([':id' => $id]);
}
}

return $payload ?? '';
}

public function close()
{
return true;
}

public function destroy($id)
{
$this->pdo
->prepare('DELETE FROM sessions WHERE `id` = :id')
->execute([':id' => $id])
;
}

public function gc($max_lifetime)
{
$sth = $this->pdo->prepare('SELECT * FROM sessions');

if ($sth->execute()) {
while ($row = $sth->fetchObject()) {
$timestamp = strtotime($row->created_at);

if (time() - $timestamp > $max_lifetime) {
$this->destroy($row->id);
}
}
return true;
}

return false;
}

public function write($id, $data)
{
return $this->
pdo->prepare('UPDATE sessions SET `payload` = :payload WHERE `id` = :id')
->execute([':payload' => $data, ':id' =>$id]);
}
}

// 세션 핸들러 등록
session_set_save_handler(new DatabaseSessionHandler(new PDO('mysql:dbname=test;host=127.0.0.1;', 'root', 'root')));
session_start();
$_SESSION['message'] = 'Hello world';
$_SESSION['foo'] = new stdClass();

session_gc(); // 세션 정리

리플렉션 (ReflectionClass) :: PHP

작성자아이디 : skok1025, 2022-09-19 21:25:23
카테고리 : Language PHP 게시글 수정

리플렉션을 통해 객체의 메타데이터 (properties, class) 를 확인이 가능하다.



/**
* ReflectionClass
*/

class A
{
private $message = "Hello world";

public function __construct($message)
{
$this->message = $message;
}
}

class B extends A
{

}
// 특정 클래스 "A" 에 대하여 private 의 properties 가져오기
$refClass = new ReflectionClass('\A');
var_dump($refClass->getProperties(ReflectionProperty::IS_PRIVATE));
==>
array(1) { [0]=> object(ReflectionProperty)#2 (2) { ["name"]=> string(7) "message" ["class"]=> string(1) "A" } } 

// B 클래스가 A 클래스의 자식클래스인지 확인 
$refClassB = new ReflectionClass('\B');
var_dump($refClassB->isSubclassOf('\A'));
==> bool(true)
// "message" 이름의 property 정보
$messageProperty = $refClass->getProperty('message');
var_dump($messageProperty);
=> 
object(ReflectionProperty)#3 (2) { ["name"]=> string(7) "message" ["class"]=> string(1) "A" }