[PHP] Slim4 / Twig / session > Web/PHP/API

본문 바로가기
사이트 내 전체검색

Web/PHP/API

[PHP] Slim4 / Twig / session

페이지 정보

작성자 sbLAB 댓글 0건 조회 2,365회 작성일 23-07-03 10:46

본문

 Slim4 session 적용 


index,php


    ...
    //session start
    session_set_cookie_params(['secure' => true, 'httponly' => true, 'samesite' => 'lax']);
    session_start();

    // [■ Twig] Set view in Container ----------------------------------------
    $container->set('view', function() {
        //$twig = Twig::create('templates', ['cache' => 'templates/cache']);    
        $twig = Twig::create('templates', ['cache' => false]);  
        $twig->getEnvironment()->addGlobal('session',$_SESSION);
        return $twig;
    });
//-----------------------------------------------------------------------

    // 1) Instantiate the app
    $app = AppFactory::create();

    // [■ Twig] Add Twig-View Middleware
    $app->add(TwigMiddleware::createFromContainer($app));
    ...
 


※ 위 index.php 는 예시로, 실 적용하면 안된다.

※ 위처럼 아래 내용을 inxex.php 에 사용할 경우 

    // [■ Twig] Set view in Container ----------------------------------------
    $container->set('view', function() {
        //$twig = Twig::create('templates', ['cache' => 'templates/cache']);    
        $twig = Twig::create('templates', ['cache' => false]);  
        $twig->getEnvironment()->addGlobal('session',$_SESSION);
        return $twig;
    });
    //-----------------------------------------------------------------------


index.php 에 설정되는 아래 DI cache 를 사용할 수 없다.

/**
 * [DI container Cache ★1]
 * Compile the container for optimum performances.
 * Should be set to true in production
 */
if (true) { //false : disabled  true: enabled
   $containerBuilder->enableCompilation(__DIR__ . '/../var/cache');
}
 


(오류) Fatal error: You cannot set a definition at runtime on a compiled container. 

You can either put your definitions in a file, disable compilation or ->set() a raw value directly (PHP object, string, int, ...) instead of a PHP-DI definition. 


[해결방법]

1) DI 캐시를 사용하지 않는다(권장 의견 다수, 대부분 이미 php Opcache 가 작동하므로)

2) index.php 에서 'view' 컨테이너를 설정(set)하지 않고,  config/di.php 파일 에서 ContainerBuilder 로 'view' 를 직접 정의해 준다.

/**
 * Dependency Injection in Slim 4
 */

    declare(strict_types=1);

    use DI\ContainerBuilder;
    use Slim\Views\Twig;

    return function (ContainerBuilder $containerBuilder) {
        $containerBuilder->addDefinitions([        
            //Twig
            'view' => function () {
                //$twig = Twig::create('templates', ['cache' => 'templates/cache']);    
                $twig = Twig::create('templates', ['cache' => false]);
                $twig->getEnvironment()->addGlobal('session', $_SESSION);
                return $twig;
            }
        ]);
    };
 



※ slim4 에서 생성되는 폴더들(캐시경로, 로그파일경로)은 nginx:nginx 소유자로 설정함( chown nginx:nginx var -R )

/var/cache    <-- DI container Cache(CompiledContainer.php), routecache 파일 생성 경로(임의 설정경로임)

/var/log      <-- Monolog log파일 생성 경로(임의 설정경로임)


dashboard.html.twig 


    {% if session.login_email is defined %}
        {{ session.login_email }}
    {% else %}
    Do something else
    {% endif %}         {{ (session.foo is defined) ? ‘defined’ : ‘not defined’ }} 
 



 php session 웹서버(nginx + php8.1-fpm) 기본세팅 


# cd /var/lib/php

# chown nginx:nginx sessions -R

# /var/lib/php/sessions  <-  755  

# /var/lib/php/sessions/*   <-  600 


  /etc/php/8.1/fpm/php.ini 설정 - https 필수 기본 환경

   [Session]
   session.use_cookies = 1
   session.cookie_secure = 1
   session.use_only_cookies = 1
   session.cookie_httponly = 1
   session.cookie_samesite = 'none' //Lax 권장 session.cookie_samesite = Lax
 


session.cookie_samesite = 'none'

5c9f22f63bd912f57102880998ea8166_1688558141_5272.jpg
 

session.cookie_samesite = Lax

7d7bb345c8bd776dad1c84837b5d1423_1688772781_6113.jpg
 


Securing Session INI Settings 

https://www.php.net/manual/en/session.security.ini.php


Slim 4 Skeleton 

https://odan.github.io/slim4-skeleton/ 


Session v6 Documentation 

https://odan.github.io/session/v6/


CSRF 공격(Cross Site Request Forgery)

https://itstory.tk/entry/CSRF-%EA%B3%B5%EA%B2%A9%EC%9D%B4%EB%9E%80-%EA%B7%B8%EB%A6%AC%EA%B3%A0-CSRF-%EB%B0%A9%EC%96%B4-%EB%B0%A9%EB%B2%95 


Slim Framework CSRF Protection

https://github.com/slimphp/Slim-Csrf


Cookie SameSite 설정 

https://ifuwanna.tistory.com/223 


구글 Chrome SameSite (Lax / CSRF)

https://velog.io/@jsj3282/%EA%B5%AC%EA%B8%80-Chrome-SameSite-%EC%9D%B4%EC%8A%88 


https://stackoverflow.com/questions/30952536/php-sessions-with-slimtwig-a-template-that-extends-another-one-cannot-have-a-b 

https://discourse.slimframework.com/t/accessing-session-variable-in-twig/4232/4


Session Based Authentication - Session Hijacking & Fixation - Build Expense Tracker App With PHP 8 

https://www.youtube.com/watch?v=nJWmoetWP0k&t=496s 



댓글목록

등록된 댓글이 없습니다.

회원로그인

접속자집계

오늘
215
어제
396
최대
1,279
전체
222,265

그누보드5
Copyright © sebom.com All rights reserved.