如何执行关闭页面上的PHP代码? [英] How can I execute PHP code on page close?

查看:173
本文介绍了如何执行关闭页面上的PHP代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法,一旦用户关闭页面,该方法即可执行一些PHP代码.在我的应用程序中,一旦用户关闭或导航离开页面,服务器将在数据库中将该用户声明为脱机".这要求代码知道用户何时离开页面.我的应用程序还承受着无尽的负担(即,它将一直休眠直到用户关闭页面为止).

I am trying to find a method to execute some PHP code once a user closes the page. In my application, once the user closes or navigates away from the page the server will state the user as 'Offline' in the database. This requires the code to know when the user has navigated away from the page. My application also has an endless load (i.e. it will sleep until the user closes the page).

推荐答案

在用户关闭页面时可靠地发送事件几乎是不可能的.有一个onbeforeunload事件可以进行Ajax调用,但是可能会失败,出于安全原因而无法执行,或者由于用户关闭了JavaScript而根本无法执行.

Reliably sending an event when the user closes the page is close to impossible. There is the onbeforeunload event that could do an Ajax call, but that could fail, not be executed for security reasons, or not be executed at all because the user has JavaScript turned off.

这通常是通过会话超时完成的:检查上一次对特定会话的请求的时间.如果时间超过x分钟前,则该会话将被视为已过期.那不是一种选择吗?

This is usually done through session timeouts: It is checked when a request for a certain session was last made. If it was longer than x minutes ago, the session is treated as expired. Is that not an option?

这篇关于如何执行关闭页面上的PHP代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆