복붙노트

30 분 후에 어떻게 PHP 세션을 만료 시키나요?

PHP

30 분 후에 어떻게 PHP 세션을 만료 시키나요?

세션을 30 분 동안 유지 한 다음 파기해야합니다.

해결법

  1. ==============================

    1.

    당신은 자신의 세션 타임 아웃을 구현해야한다. 다른 사람들이 언급 한 두 옵션 (session.gc_maxlifetime 및 session.cookie_lifetime)은 신뢰할 수 없습니다. 나는 그 이유를 설명 할 것이다.

    먼저:

    그러나 가비지 수집기는 session.gc_probability를 session.gc_divisor로 나눈 확률로 시작됩니다. 그리고 그 옵션에 대한 기본값 (각각 1과 100)을 사용하면 기회는 1 %에 불과합니다.

    음, 가비지 컬렉터가 더 자주 시작될 수 있도록이 값을 조정할 수 있습니다. 그러나 가비지 수집기가 시작되면 등록 된 모든 세션의 유효성을 검사합니다. 그리고 그것은 비용 집약적입니다.

    또한 PHP의 기본 session.save_handler 파일을 사용할 때 세션 데이터는 session.save_path에 지정된 경로의 파일에 저장됩니다. 해당 세션 처리기를 사용하면 마지막 액세스 날짜가 아니라 파일의 최종 수정일에 세션 데이터의 경과 시간이 계산됩니다.

    따라서 세션 데이터가 최근에 업데이트되지 않아서 세션 자체가 유효한 것으로 간주되는 동안 세션 데이터 파일이 삭제되는 경우도 있습니다.

    두 번째 :

    네, 맞습니다. 이것은 쿠키 수명에만 영향을 미치며 세션 자체는 여전히 유효 할 수 있습니다. 그러나 클라이언트가 아닌 세션을 무효화하는 것은 서버의 작업입니다. 그래서 이것은 아무 도움이되지 않습니다. 사실, session.cookie_lifetime을 0으로 설정하면 세션의 쿠키가 브라우저가 닫힐 때까지만 유효한 실제 세션 쿠키가됩니다.

    결론 / 최선의 해결책 :

    가장 좋은 해결책은 자체 세션 시간 초과를 구현하는 것입니다. 마지막 작업 (요청)의 시간을 나타내는 간단한 타임 스탬프를 사용하고 요청이있을 때마다 업데이트하십시오.

    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
        // last request was more than 30 minutes ago
        session_unset();     // unset $_SESSION variable for the run-time 
        session_destroy();   // destroy session data in storage
    }
    $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
    

    요청마다 세션 데이터를 업데이트하면 세션 파일의 수정 날짜가 변경되므로 세션이 가비지 수집기에서 조기에 제거되지 않습니다.

    또한 추가 타임 스탬프를 사용하여 주기적으로 세션 ID를 다시 생성하여 세션 고정과 같은 세션에 대한 공격을 피할 수 있습니다.

    if (!isset($_SESSION['CREATED'])) {
        $_SESSION['CREATED'] = time();
    } else if (time() - $_SESSION['CREATED'] > 1800) {
        // session started more than 30 minutes ago
        session_regenerate_id(true);    // change session ID for the current session and invalidate old session ID
        $_SESSION['CREATED'] = time();  // update creation time
    }
    

    노트:

  2. ==============================

    2.

    참고 : 시간을 변경하려면 원하는 시간으로 30을 변경하고 * 60을 변경하지 마십시오. 이것은 분을 나타냅니다.

    분 : (30 * 60) 일 수 : (n * 24 * 60 * 60) n = 일 수 없음

    <?php
        session_start();
    ?>
    
    <html>
        <form name="form1" method="post">
            <table>
                <tr>
                    <td>Username</td>
                    <td><input type="text" name="text"></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="pwd"></td>
                </tr>
                <tr>
                    <td><input type="submit" value="SignIn" name="submit"></td>
                </tr>
            </table>
        </form>
    </html>
    
    <?php
        if (isset($_POST['submit'])) {
            $v1 = "FirstUser";
            $v2 = "MyPassword";
            $v3 = $_POST['text'];
            $v4 = $_POST['pwd'];
            if ($v1 == $v3 && $v2 == $v4) {
                $_SESSION['luser'] = $v1;
                $_SESSION['start'] = time(); // Taking now logged in time.
                // Ending a session in 30 minutes from the starting time.
                $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
                header('Location: http://localhost/somefolder/homepage.php');
            } else {
                echo "Please enter the username or password again!";
            }
        }
    ?>
    
    <?php
        session_start();
    
        if (!isset($_SESSION['luser'])) {
            echo "Please Login again";
            echo "<a href='http://localhost/somefolder/login.php'>Click Here to Login</a>";
        }
        else {
            $now = time(); // Checking the time now when home page starts.
    
            if ($now > $_SESSION['expire']) {
                session_destroy();
                echo "Your session has expired! <a href='http://localhost/somefolder/login.php'>Login here</a>";
            }
            else { //Starting this else one [else1]
    ?>
                <!-- From here all HTML coding can be done -->
                <html>
                    Welcome
                    <?php
                        echo $_SESSION['luser'];
                        echo "<a href='http://localhost/somefolder/logout.php'>Log out</a>";
                    ?>
                </html>
    <?php
            }
        }
    ?>
    
    <?php
        session_start();
        session_destroy();
        header('Location: http://localhost/somefolder/login.php');
    ?>
    
  3. ==============================

    3.

    설정 한 시간이 지나면 사용자를 로그 아웃합니까? 세션 생성 시간 (또는 만료 시간)을 등록 할 때 설정하고 각 페이지로드시이를 확인하십시오.

    예 :

    $_SESSION['example'] = array('foo' => 'bar', 'registered' => time());
    
    // later
    
    if ((time() - $_SESSION['example']['registered']) > (60 * 30)) {
        unset($_SESSION['example']);
    }
    

    편집 : 나는 당신이 다른 것을 의미한다는 느낌이있어.

    session.gc_maxlifetime ini 설정을 사용하여 특정 수명 후 세션을 스크랩 할 수 있습니다.

    편집하다:     ini_set ( 'session.gc_maxlifetime', 60 * 30);

  4. ==============================

    4.

    이 게시물은 세션 시간 초과를 제어하는 ​​두 가지 방법을 보여줍니다. http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions

    IMHO 두 번째 옵션은 좋은 솔루션입니다 :

    <?php
    /***
     * Starts a session with a specific timeout and a specific GC probability.
     * @param int $timeout The number of seconds until it should time out.
     * @param int $probability The probablity, in int percentage, that the garbage 
     *        collection routine will be triggered right now.
     * @param strint $cookie_domain The domain path for the cookie.
     */
    function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
        // Set the max lifetime
        ini_set("session.gc_maxlifetime", $timeout);
    
        // Set the session cookie to timout
        ini_set("session.cookie_lifetime", $timeout);
    
        // Change the save path. Sessions stored in teh same path
        // all share the same lifetime; the lowest lifetime will be
        // used for all. Therefore, for this to work, the session
        // must be stored in a directory where only sessions sharing
        // it's lifetime are. Best to just dynamically create on.
        $seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
        $path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
        if(!file_exists($path)) {
            if(!mkdir($path, 600)) {
                trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
            }
        }
        ini_set("session.save_path", $path);
    
        // Set the chance to trigger the garbage collection.
        ini_set("session.gc_probability", $probability);
        ini_set("session.gc_divisor", 100); // Should always be 100
    
        // Start the session!
        session_start();
    
        // Renew the time left until this session times out.
        // If you skip this, the session will time out based
        // on the time when it was created, rather than when
        // it was last used.
        if(isset($_COOKIE[session_name()])) {
            setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
        }
    }
    
  5. ==============================

    5.

    글쎄, 위의 답변을 옳은지 이해하지만 그들은 응용 프로그램 수준에, 왜 우리는 단순히 만료 시간을 설정하는. htaccess 파일을 사용하지 않는거야?

    <IfModule mod_php5.c>
        #Session timeout
        php_value session.cookie_lifetime 1800
        php_value session.gc_maxlifetime 1800
    </IfModule>
    
  6. ==============================

    6.

    if (isSet($_SESSION['started'])){
        if((mktime() - $_SESSION['started'] - 60*30) > 0){
            //Logout, destroy session, etc.
        }
    }
    else {
        $_SESSION['started'] = mktime();
    }
    
  7. ==============================

    7.

    이것을 만드려면 session_set_cookie_paramsfunciton을 사용하십시오.

    session_start () 호출 전에이 함수를 호출해야합니다.

    이 시도:

    $lifetime = strtotime('+30 minutes', 0);
    
    session_set_cookie_params($lifetime);
    
    session_start();
    

    자세한 내용은 http://php.net/manual/function.session-set-cookie-params.php를 참조하십시오.

  8. ==============================

    8.

    다음과 같은 기능을 사용하면 실제로 쉽습니다. 'id'와 'time'필드가있는 데이터베이스 테이블 이름 'sessions'를 사용합니다.

    사용자가 사이트 나 서비스를 다시 방문 할 때마다이 함수를 호출하여 반환 값이 TRUE인지 확인해야합니다. 거짓 인 경우 사용자가 만료되어 세션이 삭제됩니다. (참고 :이 함수는 데이터베이스 클래스를 사용하여 데이터베이스에 연결하고 쿼리합니다. 물론 함수 또는 이와 유사한 것으로도 가능합니다.) :

    function session_timeout_ok() {
        global $db;
        $timeout = SESSION_TIMEOUT; //const, e.g. 6 * 60 for 6 minutes
        $ok = false;
        $session_id = session_id();
        $sql = "SELECT time FROM sessions WHERE session_id = '".$session_id."'";
        $rows = $db->query($sql);
        if ($rows === false) {
            //Timestamp could not be read
            $ok = FALSE;
        }
        else {
            //Timestamp was read succesfully
            if (count($rows) > 0) {
                $zeile = $rows[0];
                $time_past = $zeile['time'];
                if ( $timeout + $time_past < time() ) {
                    //Time has expired
                    session_destroy();
                    $sql = "DELETE FROM sessions WHERE session_id = '" . $session_id . "'";
                    $affected = $db -> query($sql);
                    $ok = FALSE;
                }
                else {
                    //Time is okay
                    $ok = TRUE;
                    $sql = "UPDATE sessions SET time='" . time() . "' WHERE session_id = '" . $session_id . "'";
                    $erg = $db -> query($sql);
                    if ($erg == false) {
                        //DB error
                    }
                }
            }
            else {
                //Session is new, write it to database table sessions
                $sql = "INSERT INTO sessions(session_id,time) VALUES ('".$session_id."','".time()."')";
                $res = $db->query($sql);
                if ($res === FALSE) {
                    //Database error
                    $ok = false;
                }
                $ok = true;
            }
            return $ok;
        }
        return $ok;
    }
    
  9. ==============================

    9.

    세션에 타임 스탬프 저장

    <?php    
    $user = $_POST['user_name'];
    $pass = $_POST['user_pass'];
    
    require ('db_connection.php');
    
    // Hey, always escape input if necessary!
    $result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($user), mysql_real_escape_string($pass));
    
    if( mysql_num_rows( $result ) > 0)
    {
        $array = mysql_fetch_assoc($result);    
    
        session_start();
        $_SESSION['user_id'] = $user;
        $_SESSION['login_time'] = time();
        header("Location:loggedin.php");            
    }
    else
    {
        header("Location:login.php");
    }
    ?>
    

    이제 타임 스탬프가 허용 된 시간 범위 내에 있는지 확인하십시오 (1800 초는 30 분입니다)

    <?php
    session_start();
    if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800)
    {
        header("Location:login.php");
    }
    else
    {
        // uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login
        //$_SESSION['login_time'] = time();
        echo ( "this session is ". $_SESSION['user_id'] );
        //show rest of the page and all other content
    }
    ?>
    
  10. ==============================

    10.

    모든 페이지에로드 된 포함 파일에서 다음 코드 블록을 사용하십시오.

    $expiry = 1800 ;//session expiry required after 30 mins
        if (isset($_SESSION['LAST']) && (time() - $_SESSION['LAST'] > $expiry)) {
            session_unset();
            session_destroy();
        }
        $_SESSION['LAST'] = time();
    
  11. ==============================

    11.

    타임 스탬프 사용 중 ...

    <?php
    if (!isset($_SESSION)) {
        $session = session_start();
    } 
    if ($session && !isset($_SESSION['login_time'])) {
        if ($session == 1) {
            $_SESSION['login_time']=time();
            echo "Login :".$_SESSION['login_time'];
            echo "<br>";
            $_SESSION['idle_time']=$_SESSION['login_time']+20;
            echo "Session Idle :".$_SESSION['idle_time'];
            echo "<br>";
        } else{
            $_SESSION['login_time']="";
        }
    } else {
        if (time()>$_SESSION['idle_time']){
            echo "Session Idle :".$_SESSION['idle_time'];
            echo "<br>";
            echo "Current :".time();
            echo "<br>";
            echo "Session Time Out";
            session_destroy();
            session_unset();
        } else {
            echo "Logged In<br>";
        }
    }
    ?>
    

    타임 스탬프를 사용하여 세션을 만료시키기 위해 20 초를 사용했습니다.

    30 분이 필요하면 1800 (초당 30 분) 추가 ...

  12. from https://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes by cc-by-sa and MIT lisence