dongxi5423 2019-01-10 16:05
浏览 42
已采纳

删除过期的会话

This is my first time posting. I believe I've searched through a bit of the other forums to see if my question has already been asked, but I'm still left scratching my head. I know there's a lot of postings about expired sessions, but I'm thinking in terms of a specific scenario, I guess.

A user is logged into the Dashboard and goes to a page. It sits idle for how ever long, then the garbage collector does its thing and clears the session.

Now, if the user goes back to the Dashboard and clicks to go to another page, I would like to have the user return to the index page - effectively log out.

I have a logout page that the user can go to when they choose to log out. I record some data in the database, remove the session and redirects back to the home page.

I would like to first check if the session is indeed alive. If not, destroy it and redirect to the home page. Otherwise, delete it.

But my question is, if the garbage collector had already cleared the session, do I even need to destroy it?

<?php 

  session_start( );

  if( !isset( $_SESSION['session'] ) ) { 
     session_destroy( );
     header( "Location: /index.php" );
  }
  else {

     // ... log the data I need in the database ...

     $_SESSION['session'] = array( );

     if( ini_get( "session.use_cookies" ) ) {
       $params = session_get_cookie_params( );
       setcookie( session_name( ), '', time( ) - 42000,
                  $params["path"], $params["domain"],
                  $params["secure"], $params["httponly"] );
     }

     session_destroy( );
     header( "Location: /index.php" );    
  }

?>
  • 写回答

2条回答 默认 最新

  • dongtu1789 2019-01-10 16:12
    关注

    session_start() and session_destroy() aren't working with the garbage collector the way you think they are. They're utilizing internal adapters to allow PHP to talk to a persistence layer (generally the filesystem, in this case, the browsers cookies), to extract session information.

    What you're doing when you call session_destroy(), is you're instructing your session ADAPTER to destroy the session, not so much PHP. PHP garbage collects the session memory usage constantly, but still maintains reference to the adapters persistence of the session data.

    So, yes, you have to call it, unless you destroyed it already.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line