관리 메뉴

투덜이 개발자

[PHP] 세션 처리 본문

Program Language/PHP

[PHP] 세션 처리

엠투 2026. 2. 24. 16:39
반응형

30분(inactivity) 지나면 강제 로그아웃

 

1) 공통 include 파일: session_guard.php

<?php
// session_guard.php
// 모든 보호가 필요한 페이지/요청의 맨 위에서 include 하세요.

$INACTIVITY_LIMIT = 1800; // 30분 (초)

// 세션 쿠키를 30분 유지로 맞추고 싶다면(선택):
// 브라우저 종료해도 30분 유지가 필요할 때만 사용.
// 보안 요구가 높으면 0(브라우저 종료 시 삭제) 권장.
ini_set('session.cookie_lifetime', (string)$INACTIVITY_LIMIT);

// 세션 시작 전 옵션(선택): PHP 7.4에서도 동작
session_name('SID');
session_start();

// 1) inactivity 체크
$now = time();

if (isset($_SESSION['last_activity'])) {
    $idle = $now - (int)$_SESSION['last_activity'];

    if ($idle > $INACTIVITY_LIMIT) {
        // 만료 처리: 세션 파기 + 쿠키 제거 + 리다이렉트
        session_unset();
        session_destroy();

        // 세션 쿠키 제거
        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 3600,
                $params['path'] ?? '/',
                $params['domain'] ?? '',
                (bool)($params['secure'] ?? false),
                (bool)($params['httponly'] ?? true)
            );
        }

        // 만료 사유 전달(선택)
        header('Location: /login.php?reason=timeout');
        exit;
    }
}

// 2) 마지막 활동 시간 갱신
$_SESSION['last_activity'] = $now;

// 3) 로그인 여부 체크(예시)
// 로그인 세션키를 쓰는 방식에 맞게 수정하세요.
if (empty($_SESSION['user_id'])) {
    header('Location: /login.php?reason=login_required');
    exit;
}

 

2) 보호가 필요한 모든 페이지에서 사용

예: dashboard.php

<?php
require_once __DIR__ . '/session_guard.php';

// 여기부터 보호된 컨텐츠
echo "Hello, user #" . (int)$_SESSION['user_id'];

 

3) 로그인 처리 예시: login.php (아주 단순)

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // TODO: 실제로는 DB/인증 로직 넣기
    $id = trim($_POST['id'] ?? '');
    $pw = trim($_POST['pw'] ?? '');

    if ($id === 'admin' && $pw === 'pass') {
        // 로그인 성공
        session_regenerate_id(true); // 세션 고정 공격 방지

        $_SESSION['user_id'] = 1;
        $_SESSION['last_activity'] = time();

        header('Location: /dashboard.php');
        exit;
    }

    $error = 'Invalid credentials';
}
?>
<!doctype html>
<html>
<body>
<?php if (!empty($_GET['reason'])): ?>
  <p>Reason: <?= htmlspecialchars($_GET['reason'], ENT_QUOTES, 'UTF-8') ?></p>
<?php endif; ?>
<?php if (!empty($error)): ?>
  <p style="color:red;"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p>
<?php endif; ?>

<form method="post">
  <input name="id" placeholder="id">
  <input name="pw" placeholder="pw" type="password">
  <button type="submit">Login</button>
</form>
</body>
</html>

 

반응형