세션 처리 SessionHandlerInterface 클래스
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
소개
SessionHandlerInterface는 사용자 정의 세션 핸들러를 생성하기 위한 최소한의 프로토타입을 정의하는 인터페이스입니다. OOP 호출을 사용하여 사용자 정의 세션 핸들러를 session_set_save_handler()에 전달하기 위해 클래스는 이 인터페이스를 구현할 수 있습니다.
이 클래스의 콜백 메서드는 PHP에서 내부적으로 호출하도록 설계되었으며 사용자 공간 코드에서 호출할 수 없습니다.
클래스 개요
interface SessionHandlerInterface {
/* Methods */
public close(): bool
public destroy(string $id): bool
public gc(int $max_lifetime): int|false
public open(string $path, string $name): bool
public read(string $id): string|false
public write(string $id, string $data): bool
}
예제 #1 SessionHandlerInterface를 사용한 예
다음 예제는 PHP 세션의 기본 저장 핸들러 files
과 유사한 파일 기반 세션 저장소를 제공합니다. 이 예제는 선호하는 PHP 지원 데이터베이스 엔진을 사용하여 데이터베이스 스토리지를 다루도록 쉽게 확장될 수 있습니다.
session_set_save_handler()와 함께 OOP 프로토타입을 사용하고 함수의 매개변수 플래그를 사용하여 종료 함수를 등록합니다. 이것은 일반적으로 객체를 세션 저장 핸들러로 등록할 때 권장됩니다.
주의 간결함을 위해 이 예제에서는 입력 유효성 검사를 생략합니다. 그러나 $id
매개변수는 실제로 경로 탐색 문제와 같은 취약점을 피하기 위해 적절한 유효성 검사/위생 처리가 필요한 사용자 제공 값입니다. 따라서 프로덕션 환경에서 수정되지 않은 이 예제를 사용하지 마십시오.
<?php
class MySessionHandler implements SessionHandlerInterface
{
private $savePath;
public function open($savePath, $sessionName): bool
{
$this->savePath = $savePath;
if (!is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}
return true;
}
public function close(): bool
{
return true;
}
#[ReturnTypeWillChange]
public function read($id)
{
return (string)@file_get_contents("$this->savePath/sess_$id");
}
public function write($id, $data): bool
{
return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
}
public function destroy($id): bool
{
$file = "$this->savePath/sess_$id";
if (file_exists($file)) {
unlink($file);
}
return true;
}
#[ReturnTypeWillChange]
public function gc($maxlifetime)
{
foreach (glob("$this->savePath/sess_*") as $file) {
if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
unlink($file);
}
}
return true;
}
}
$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();
// proceed to set and retrieve values by key from $_SESSION
목차
- SessionHandlerInterface::close — 세션 닫기
- SessionHandlerInterface::destroy — 세션 파괴
- SessionHandlerInterface::gc — 오래된 세션 정리
- SessionHandlerInterface::open — 세션 초기화
- SessionHandlerInterface::read — 세션 데이터 읽기
- SessionHandlerInterface::write — 세션 데이터 쓰기