1

Possible Duplicate:
Detecting Browser exit in PHP

I have some user related files in my server and I want them to be deleted when user closes the browser or leaves my page. Is it possible? Is there any way to do it?

Community
  • 1
  • 1
ATZ
  • 353
  • 2
  • 7
  • 18

3 Answers3

1

Not just with PHP.

PHP runs server-side, and is far done processing your page by the time the user will have a chance to close their browser. You could technically detect if PHP was still processing the page and the user closes it, with a specific configuration. However, it is not ideal. See connection_aborted().

What you need to do is set up a long-polling connection with JavaScript, and monitor it server-side. You will then get an idea for when that window is closed. That connection could be made to your PHP script, allowing PHP to check connection_aborted(). Note that you will need to set up ignore_user_abort() for this to work, or configure PHP.ini accordingly.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • Thank but how to set up long-polling connection? Is it like JavaScript keep detecting whether browser is still open and once it cannot detect anymore, it inform server side to delete the files? – ATZ Aug 18 '12 at 16:20
  • @ATZ, JavaScript runs client-side in your browser. Basically, you make an AJAX request to the server. The server accepts the connection, and does nothing. If you are worried about broken browsers, you can send a byte of meaningless data every 10 seconds or so to show that the server has not timed out, but this is rarely (ever?) necessary. When the client disconnects, you know that your page isn't running anymore. It is also common to keep that connection open for somewhere between 30 seconds and one minute, and then establish a new one. – Brad Aug 18 '12 at 16:31
0

You could use javascript to make an ajax call to a .php file every few seconds.

Makita
  • 1,812
  • 12
  • 15
  • 2
    There is a **ton** of overhead with this approach, and is not recommended. – Brad Aug 18 '12 at 16:10
  • Depends on the application scale and implementation doesn't it? Long polling is not necessarily a default win. – Makita Aug 18 '12 at 16:17
0

PHP is *server*side so with only PHP this isn't possible in most cases. A possible solution would be to let a cronjob run everynight and let it delete the old files.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262