简体   繁体   中英

How to log out an user in php?

Currently, in my php script, after an user logged in, i stored session_login = 1. But I have a problem. I have a habit in using firefox, multi-tab (i believe most people and all today web browsers app have multi-tab function). I closed the tab that has the session, but I didnt closed the browser. After few hours, I come back on the same page that require me to login, but it doesn't. It does not require me to login again(I think thats called "Session"). Is there anyway to logout the user if he close the tab instead close the browser??

I have 1 solution right now, time-idle kick out. But, I have very limited knowledge in date/time thing in php, so this would be the last option. I wanted to know, is there anything else i can do, beside using time-idle?

PHP has an easy way to set how long a session will last before it times out:

session_set_cookie_params(3600); // make it expire after 1 hour

Just pass it the number of seconds you want the session to last (in the example, 1 hour = 60 minutes = 3600 seconds).

http://us2.php.net/manual/en/function.session-set-cookie-params.php

A session cookie is only cleared from the browser when the browser session is closed (ie when the browser is closed): hence the name. If you want the session to be cleared shortly after the tab is closed you could set a very short expiry time on the cookie (around 5 minutes) and store the same in the database. Then have a javascript function on the web page calling a file from your server every minute: this file then "refreshes" the cookie/database entry for the next five minutes. If they then leave your site for more than five minutes, then the session is invalidated.

You could also add a Javascript "onunload" function which detects if they have closed the webpage or gone to another page: you could add a hook on this to call a "destroycookie" function - however, you'll have to check that they haven't just gone to another page on your site and don't actually have two pages from your site open in two tabs.

I believe the option you are looking for is the setting for the session cookie expiration. I don't remember the PHP command for it, but you should be able to set the cookie to expire when the window closes.

Here is the PHP session documentation: http://us2.php.net/manual/en/book.session.php

也许您可以使用session_write_close()?

在session_destroy函数的PHP文档中有一条注释可能对您有用: http : //us2.php.net/manual/en/function.session-destroy.php#71889

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM