기본 설정 확인
1. PHP 세션 설정
// 세션 시작 전 설정
ini_set('session.save_handler', 'files');
ini_set('session.save_path', '/tmp');
session_start();
2. 권한 설정
chmod 777 /tmp
세션 초기화 코드
// 세션 시작과 기본값 설정
session_start();
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = [
'id' => null,
'login_time' => time()
];
}
세션 핸들러 구현
class CustomSessionHandler implements SessionHandlerInterface {
private $savePath;
public function open($savePath, $sessionName) {
$this->savePath = $savePath;
return true;
}
public function write($id, $data) {
return file_put_contents(
"$this->savePath/sess_$id",
$data
) === false ? false : true;
}
public function read($id) {
return (string)@file_get_contents(
"$this->savePath/sess_$id"
);
}
}
데이터베이스 세션 저장
class DatabaseSessionHandler implements SessionHandlerInterface {
private $db;
public function write($id, $data) {
$sql = "INSERT INTO sessions (id, data, timestamp)
VALUES (:id, :data, :time)
ON DUPLICATE KEY UPDATE
data = :data, timestamp = :time";
$stmt = $this->db->prepare($sql);
return $stmt->execute([
'id' => $id,
'data' => $data,
'time' => time()
]);
}
}
세션 상태 확인
function checkSession() {
return [
'session_status' => session_status(),
'session_id' => session_id(),
'session_save_path' => session_save_path(),
'session_data' => $_SESSION
];
}
모범 사례
- 세션 시작 전 출력 방지
- 적절한 세션 만료 시간 설정
- 안전한 세션 ID 생성
- 정기적인 세션 정리
구현 예시
// 세션 설정과 시작
session_set_cookie_params([
'lifetime' => 3600,
'path' => '/',
'domain' => '',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
session_start();
// 세션 데이터 저장
$_SESSION['user_id'] = 123;
$_SESSION['last_activity'] = time();