How to determine if a user leaves a page in PHP

There is such a function that I want to execute if the user leaves a specific page. This function will basically change all the data in a specific column in my database. Therefore, if the user leaves this page, I want this function to be performed by the system. Is there any way to detect that the user has already left the page.

Thanks!

+6
source share
4 answers

With 100% reliability, no, that’s not possible. Since leaving a specific page on the client side, you have 0 control over what the client does. You can register the onbeforeunload handler through Javascript and hope the browser supports it. But again, support for this is not universal.

+5
source

You cannot do this with PHP, as it is a server language. You will need to use JavaScript.

+1
source

You cannot do this in php, but you can use the javascript function onbeforeunload, here is an example

 <script type="text/javascript"> window.onbeforeunload = confirmExit; function confirmExit() { return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?"; } </script> 
+1
source

Since php on the server side only starts the server script and then sends the result to the browser, you cannot do this with php. You can send an ajax request to your PHP script with the onunload event using javascript, and then run the PHP script in response to this request.

+1
source

Source: https://habr.com/ru/post/918052/


All Articles