0

I have a login form where a unique key is generated for every page refresh. The database table contains a flag field. If it is 0 then user is not logged in and 1 means logged in. So without refreshing the page how can I check my database every 5 seconds to see if a flag is set or not?

I tried using sleep(5) but it prevent page from loading or rather it sleeps for 5 seconds then load the page. Is there a way to acheive this?

Sam Pro
  • 73
  • 6
  • 1
    You would likely have to use JavaScript and AJAX. – Jay Blanchard Oct 12 '15 at 18:32
  • this may help you to call ajax with every 5 seconds interval http://stackoverflow.com/questions/5687600/jquery-call-ajax-every-10-seconds – A l w a y s S u n n y Oct 12 '15 at 18:35
  • Ajax request is the simplist way. Write another script that checks the database and returns true or false depending on the value found. By the way, I know this sounds strange, but I would run it every 8 to 10 seconds to avoid possible request clashes. – worldofjr Oct 12 '15 at 18:37
  • You don't want PHP to wait or sleep, PHP has a maximum execution time (default 30 seconds), as everyone tells you - Use JS. – SebHallin Oct 12 '15 at 18:41

1 Answers1

1

You need to have 2 pages:

  1. The page your users access (also the page you add the jQuery code below)
  2. The page which reads your database and prints out true/false (Which in the example below, I am naming it as "your_check_login_url.php".)

The jQuery code on page 1 will read page 2 without refreshing page 1. You then use Javascript to update what you need on page 1.

Using jQuery:

<script>
var tid = setTimeout(checkLogin, 5000);
function checkLogin() {
    $.get( "your_check_login_url.php", function( data ) {
        alert(data.is_logged_in); // Replace with your own code
    });
    tid = setTimeout(checkLogin, 5000); // repeat myself
}
</script>

And on the PHP side return a value JSON or otherwise which your Javascript can read as true/false.

<?php
$logged_in = TRUE; //Replace with your PHP/MySQL code to check if log in is true
header('Content-Type: application/json');
echo json_encode(
    array('is_logged_in' => $logged_in)
);
JC Lee
  • 2,337
  • 2
  • 18
  • 25
  • Can you add some hints on how to access data objects from MYSQL->PHP->JSON->jQuery? I'm confused of how this works. – Sam Pro Oct 12 '15 at 18:45
  • @SamPro Basically, you need 2 pages to do this. One page which the users see (where you add the jQuery code) and another page which reads from the database and prints out true/false. – JC Lee Oct 12 '15 at 18:52