I have a site where i sell streaming videos, and i’m currently using a plugin that prevents account sharing by allowing only one device logged at a time. The problem is, the user can start watching the stream and then share his account, the second person will access the stream and both of them will watch because User 1 didn’t refresh the page (which will log him out).
How can i make the site automatically check every x minutes if user 1 is still logged in and if he isn’t, refresh the page?
2
Answers
One way to do this would be to have the page call out to you on an interval using Javascript asynchronously. (e.g. ajax)
Depending on how the streaming works you could even terminate further streaming if you do not get the interval call after a set amount of time.
First of all, this is a great question !
The problem here is to periodically check if a user is logged in, tho as you understand PHP doesn’t refresh on its own.
Like @Chris Haas pointed out, the following article "Check if user is logged in using JQuery" is pretty close to the behavior you’re looking for, tho we need to set up, and understand a few thing.
We can pass variable from PHP to Javascript through the wp_localize_script() WordPress function…
…Tho, if we just localize the
is_user_logged_in()
as a variable, then the function would only be trigger once, meaning when the script is actually enqueued.The answer to our problem is triggering back a PHP function from our Javascript through Ajax.
From our
function.php
: Since Ajax is already built into the core WordPress administration screens, passing it to the front end is fairly easy.Keep in mind that Ajax is dependend on JQuery, that’s why
my-script.js
is depended on JQuery.From our
my-script.js
: Our Ajax request is wrapped in a setInterval method firing every seconds. If the answer sent from the matching PHP function isfalse
we force reload the whole page throughlocation.reload()
.From our
function.php
: The matching PHP function will check if the user is logged-in upon receiving the request sent by our self triggering Ajax function.It will send back a response containing the user status (
true
/false
).