0

Is there a way that I can run a php command if a window is closed?

For example, I have a script that the user uses to upload files to a temp directory on the server ready for the user to decide if they want to keep them or not. However, as it stands at the moment, if the user just leaves the page the files stay there.

Thanks

tatty27
  • 1,553
  • 4
  • 34
  • 73
  • 1
    You can use javascript to detect if window is closed. If true do ajax call to your script. – GGio Feb 04 '13 at 18:43

3 Answers3

1

You may add a javascript that warns the user before leaving the page using onBeforeUnload, some examples can be found here:

JavaScript + onbeforeunload

Community
  • 1
  • 1
thaJeztah
  • 27,738
  • 9
  • 73
  • 92
0

You might be able to intercept the page exit event in javascript and pass that to your php application: Intercept page exit event

This seems like it would be better implemented as a cron job on the server that would cleanup files in a temp directory.

Community
  • 1
  • 1
tdedecko
  • 1,442
  • 10
  • 15
0

PHP scripts have to be initialized by "something". With that said:

You may consider a CRON job that runs every so often and runs a PHP script for you. Lets say for example you wanted to 'clear' the temp directory every half hour, a CRON job would work perfectly for that. -- The reason JavaScript might not be your best bet here is, like you said, if the user closes the window, JavaScript ceases to function.

Zak
  • 6,976
  • 2
  • 26
  • 48
  • Thanks, I thought of that but if a user is part way through uploading their files it would get rid of the ones they have done before they have finished – tatty27 Feb 04 '13 at 18:45
  • Yes, I understand. However, you can't control a user leaving before a process is completed. All you can do is try your best to "guess" what "leaving" meant. If it means "save" then CRON that. If it means "Nah I don't want them" then CRON that. It may mean "This is taking to long". The point is that every situation will be different and you won't "know" what the user wanted unless you do a little more research and possibly some user critiquing etc... `SESSION` storage may be an alternative here as well. With a "you left off here, would you like to..." Just a thought ... – Zak Feb 04 '13 at 18:51