PHP에서 세션 시간 초과를 변경하는 방법은 무엇입니까?
PHP에서 세션 시간 초과를 연장하고 싶습니다
php.ini 파일을 수정하면 가능하다는 것을 알고 있습니다. 그러나 나는 그것에 접근 할 수 없다.
PHP 코드로만 할 수 있습니까?
세션 타임 아웃은 엄격한 보증을 원한다면 코드로 구현되어야하는 개념입니다. 이것이 X 분 동안 활동이 없으면 세션이 지속되지 않을 것이라는 확신을 가질 수있는 유일한 방법 입니다.
이 요구 사항을 약간 완화하는 것이 허용되며 기간에 엄격한 제한 대신 하한 을 두는 것이 좋으면 사용자 지정 논리를 작성하지 않고도 쉽게 할 수 있습니다.
편안한 환경에서의 편리함 : 방법과 이유
경우 사용자의 세션이 (그들은 아마도) 쿠키로 구현되며, 경우 클라이언트가 악의적이지, 당신이 설정할 수 있습니다 상위 특정 매개 변수를 조정하여 세션 기간에 바인딩됩니다. 쿠키와 함께 PHP의 기본 세션 처리를 사용하는 경우 다음 session.gc_maxlifetime
과 같이 설정 session_set_cookie_params
하면 작동합니다.
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
session_start(); // ready to go!
이 기능은 최소 1 시간 동안 비활성 상태로 세션 데이터를 유지하도록 서버를 구성하고 클라이언트에게 동일한 시간 범위 후에 세션 ID를 "잊어 버려야"한다고 지시합니다. 예상 결과를 얻으려면이 두 단계가 모두 필요합니다.
한 시간 후에 클라이언트에게 세션 ID를 잊도록 지시하지 않으면 (또는 클라이언트가 악의적이며 지침을 무시하도록 선택한 경우) 동일한 세션 ID를 계속 사용하며 유효 기간은 결정적이지 않습니다. 서버 측에서 수명이 만료 된 세션은 즉시 가비지 수집되지 않고 세션 GC가 시작될 때마다 가비지 수집되기 때문 입니다 .
GC는 잠재적으로 비용이 많이 드는 프로세스이므로 일반적으로 확률은 다소 적거나 0입니다 (많은 적중 횟수를 얻은 웹 사이트는 아마도 확률 적 GC를 포기하고 매 X 분마다 백그라운드에서 발생하도록 예약합니다). 두 경우 모두 (비 협력 클라이언트 가정) 유효 세션 수명의
session.gc_maxlifetime
하한은이지만 상한은 예측할 수 없습니다.session.gc_maxlifetime
동일한 시간 범위로 설정하지 않으면 서버는 그 이전의 유휴 세션 데이터를 버릴 수 있습니다. 이 경우 여전히 세션 ID를 기억하는 클라이언트는 세션 ID를 표시하지만 서버는 해당 세션과 연관된 데이터를 찾지 못하므로 세션이 방금 시작된 것처럼 효과적으로 작동합니다.
중요한 환경에서의 확실성
사용자 지정 논리를 사용하여 세션 비 활동에 상한을 두어 사물을 완전히 제어 할 수 있습니다 . 위의 하한과 함께이 설정은 엄격하게 설정됩니다.
나머지 세션 데이터와 함께 상한을 저장하여이를 수행하십시오.
session_start(); // ready to go!
$now = time();
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
// this session has worn out its welcome; kill it and start a brand new one
session_unset();
session_destroy();
session_start();
}
// either new or old, it should live at most for another hour
$_SESSION['discard_after'] = $now + 3600;
세션 ID 지속성
지금까지 우리는 각 세션 ID의 정확한 값에 전혀 관심이 없었으며 필요한만큼 데이터가 존재해야한다는 요구 사항 만있었습니다. (아마도) 세션 ID가 중요한 경우, session_regenerate_id
필요할 때 세션 ID를 재생성하도록주의를 기울여야합니다 .
PHP의 기본 세션 처리를 사용하는 경우 모든 플랫폼에서 세션 지속 시간을 안정적으로 변경하는 유일한 방법은 php.ini 를 변경하는 것 입니다. 일부 플랫폼에서는 가비지 수집이 php.ini 에서 직접 읽는 특정 시간마다 실행되는 스크립트 ( cron 스크립트)를 통해 구현 되므로 런타임에이를 변경하려는 시도 (예 : via )는 신뢰할 수없고 가능성이 높기 때문입니다. 작동하지 않습니다.ini_set()
예를 들어, 데비안 리눅스 시스템에서, PHP의 내부 가비지 수집은 설정 session.gc_probability=0
에서 기본적 으로 설정 하여 비활성화되며 , 대신 XX : 09와 XX : 39에서 실행되는 /etc/cron.d/php를 통해 수행됩니다 (즉, 30 분마다). 이 cron 작업은 구성에 지정된 session.gc_maxlifetime 보다 오래된 세션을 찾고 발견 된 경우 삭제됩니다. 결과적으로 이러한 시스템 ini_set('session.gc_maxlifetime', ...)
에서는 무시됩니다. 또한이 질문에서 이유를 설명합니다. PHP 세션 시간이 너무 빨리 초과 되어 OP가 한 호스트에 문제가 있었지만 다른 호스트로 전환 할 때 문제가 중단되었습니다.
따라서 php.ini에 액세스 할 수 없기 때문에 이식 가능하게하려면 기본 세션 처리를 사용하는 것이 옵션이 아닙니다. 쿠키 수명을 연장하는 것은 호스트에게는 충분했지만 호스트를 전환하더라도 안정적으로 작동하는 솔루션을 원한다면 다른 대안을 사용해야합니다.
사용 가능한 대체 방법은 다음과 같습니다.
Set a different session (save) handler in PHP to save your sessions in a different directory or in a database, as specified in PHP: Custom Session Handlers (PHP manual), so that the cron job doesn't reach it, and only PHP's internal garbage collection takes place. This option probably can make use of
ini_set()
to set session.gc_maxlifetime but I prefer to just ignore the maxlifetime parameter in mygc()
callback and determine maximum lifetime on my own.Completely forget about PHP internal session handling and implement your own session management. This method has two main disadvantages: you will need your own global session variables, so you lose the advantage of the
$_SESSION
superglobal, and it needs more code thus there are more opportunities for bugs and security flaws. Most importantly, the session identifier should be generated out of cryptographically secure random or pseudorandom numbers to avoid session ID predictability (leading to possible session hijacking), and that is not so easy to do with PHP portably. The main advantage is that it will work consistently in all platforms and you have full control over the code. That's the approach taken e.g. by the phpBB forum software (at least version 1; I'm not sure about more recent versions).
There is an example of (1) in the documentation for session_set_save_handler()
. The example is long but I'll reproduce it here, with the relevant modifications necessary to extend the session duration. Note the inclusion of session_set_cookie_params()
to increase the cookie lifetime as well.
<?php
class FileSessionHandler
{
private $savePath;
private $lifetime;
function open($savePath, $sessionName)
{
$this->savePath = 'my_savepath'; // Ignore savepath and use our own to keep it safe from automatic GC
$this->lifetime = 3600; // 1 hour minimum session duration
if (!is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}
return true;
}
function close()
{
return true;
}
function read($id)
{
return (string)@file_get_contents("$this->savePath/sess_$id");
}
function write($id, $data)
{
return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
}
function destroy($id)
{
$file = "$this->savePath/sess_$id";
if (file_exists($file)) {
unlink($file);
}
return true;
}
function gc($maxlifetime)
{
foreach (glob("$this->savePath/sess_*") as $file) {
if (filemtime($file) + $this->lifetime < time() && file_exists($file)) { // Use our own lifetime
unlink($file);
}
}
return true;
}
}
$handler = new FileSessionHandler();
session_set_save_handler(
array($handler, 'open'),
array($handler, 'close'),
array($handler, 'read'),
array($handler, 'write'),
array($handler, 'destroy'),
array($handler, 'gc')
);
// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');
session_set_cookie_params(3600); // Set session cookie duration to 1 hour
session_start();
// proceed to set and retrieve values by key from $_SESSION
Approach (2) is more complicated; basically, you have to re-implement all session functions on your own. I won't go into details here.
Adding comment for anyone using Plesk having issues with any of the above as it was driving me crazy, setting session.gc_maxlifetime from your PHP script wont work as Plesk has it's own garbage collection script run from cron.
I used the solution posted on the link below of moving the cron job from hourly to daily to avoid this issue, then the top answer above should work:
mv /etc/cron.hourly/plesk-php-cleanuper /etc/cron.daily/
https://websavers.ca/plesk-php-sessions-timing-earlier-expected
Put $_SESSION['login_time'] = time();
into the previous authentication page. And the snipped below in every other page where you want to check the session time-out.
if(time() - $_SESSION['login_time'] >= 1800){
session_destroy(); // destroy session.
header("Location: logout.php");
die(); // See https://thedailywtf.com/articles/WellIntentioned-Destruction
//redirect if the page is inactive for 30 minutes
}
else {
$_SESSION['login_time'] = time();
// update 'login_time' to the last time a page containing this code was accessed.
}
Edit : This only works if you already used the tweaks in other posts, or disabled Garbage Collection, and want to manually check the session duration. Don't forget to add die()
after a redirect, because some scripts/robots might ignore it. Also, directly destroying the session with session_destroy()
instead of relying on a redirect for that might be a better option, again, in case of a malicious client or a robot.
No. If you don't have access to the php.ini, you can't guarantee that changes would have any effect.
그래도 세션 시간을 연장해야한다고 의심합니다.
현재 시간이 꽤 합리적이며 시간을 연장 할 이유가 없습니다.
을 사용하여 PHP 코드에서 php.ini의 값을 무시할 수 있습니다 ini_set()
.
참고 URL : https://stackoverflow.com/questions/8311320/how-to-change-the-session-timeout-in-php
'Programing' 카테고리의 다른 글
문자열에 적어도 하나의 소문자, 대문자, 숫자 및 기호가 포함되어 있는지 확인 (0) | 2020.06.19 |
---|---|
변수에 이름이 지정된 JavaScript 함수 호출 (0) | 2020.06.19 |
텍스트 OpenCV 추출 (0) | 2020.06.19 |
LEFT OUTER JOIN은 왼쪽 테이블에있는 것보다 더 많은 레코드를 어떻게 반환 할 수 있습니까? (0) | 2020.06.19 |
Eclipse, Android에서 가상 장치를 삭제할 수 없습니다 (0) | 2020.06.19 |