el ninho
el ninho

Reputation: 4233

How to close a session in PHP when the browser is closed?

I need to close a session when the browser is closed, when it crashes, when a PC restarts, and so on.

I know there is cookie solution, but I need something secure, server side, because the user can delete the cookie.

Upvotes: 2

Views: 5425

Answers (4)

Rupal
Rupal

Reputation: 1109

Hi You don't need to close session. because its default behavior of session that it destroy the session when user close the browser. And we can alter this behavior by changing lifetime of session in php.ini file by doing session.cookie_lifetime = 0. Otherwise by default when you reopen the browser there will be no data in session.

Upvotes: 0

Oliver A.
Oliver A.

Reputation: 2900

This can not be done the way you imagine it. You can not directly react to such an event in php. The closest you can get is using ajax to keep the session alive.

  1. Create a small php script which does nothing but update $_SESSION['last_request'] lets call it pulse.php
  2. Insert a javascript in you pages which sends a request to yourdomain.com/api/pulse.php every 60 seconds.
  3. Check if the last request uis older than 70 seconds on every request if it is start your clean up script and kill the session. If the browser crashes your cleanup script will not run. The session will timeout the usual way unless you get a request after more than 70 seconds but before the session expires. You can fix this if you store the session data in a database. Then you can run a worker or a cronjob which regularly checks if there are sessions where the last request was more than 70 seconds ago. Why 70 seconds? If you expect a request once per minute you should allow some time for klatencys or slow hardware on the client side.

Upvotes: 2

Damien Overeem
Damien Overeem

Reputation: 4529

You dont have to. The garbage collector will clean up your sessions.

The php ini setting session.gc_maxlifetime determins how long a session can remain active.

When this value is exceeded the session is automatically removed.

Upvotes: 3

smpl
smpl

Reputation: 26

cookie delete automatic when user run crashed brouser.

in php no way to know when user close brouser.

some not easy way it's websocket and long poling connections, but it's not easy to configuration and not good idea.

Upvotes: -1

Related Questions