" - I would like to know how to keep checking the value of $ _SESSION ['logout'] every 5 seconds without reloading the page, and when its value is on it redirect." p>
This can be done with ajax requests executed within a setInterval()
function. See my example:
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Verificar valor de $_SESSION['logout'] por LipESprY</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script></head><body><p>Umapáginaqualquer...</p><scripttype="text/javascript">
$(function(){
setInterval(function(){
$.ajax({
url: 'logout_status.php',
method: 'get',
dataType: 'json'
})
.done(function(retorno){
if (retorno.logout == 'on')
window.location.href = 'login.php';
})
.fail(function(erro){
console.log('Ocorreu um erro ao checar o logout:');
console.log(erro);
});
}, 5000);
});
</script>
</body>
</html>
logout_status.php:
<?php
//session_start();
//$_SESSION['logout'] = 'on';
if (!empty($_SESSION['logout']))
echo json_encode(
array('logout' => $_SESSION['logout'])
);
else
echo json_encode(
array('logout' => null)
);
Example Considerations:
- I'm using the jQuery 3.3.1 library
- On the page that addresses the ajax request (logout_status.php) I left two commented lines to test the redirect. Tailor to your project ...
- In the
setInterval()
fault function, I set the time set to 5 seconds / 5000 ms. If you want to change, just change this line: }, 5000);
. Remember that the function waits for the time in microseconds (ms);
- I've already left the redirect pointing to the file
login.php
;
- The file
logout_status.php
must be in the same directory as index.php
(side-by-side);
You can download this project from my GitHub / LipESprY / sopt-check -value-of-sessionlogout-no-update-to-page .