"- I would like to know how to check the value of $_SESSION['logout'] every 5 seconds without reloading the page, and when its value is on it redirect."
This can be done with requests ajax executed within a function setInterval()
. Take 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>Uma página qualquer...</p>
<script type="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)
);
Considerations on the example:
- I’m using the library jQuery 3.3.1;
- On the page that handles the request of ajax (logout_status.php) I left two lines commented in order to test the redirect. Adapt according to your project...
- In function
setInterval()
left time set at 5 seconds/5000 ms. If you want to change, just change this line: }, 5000);
. Remember that the function waits the time in microseconds (ms);
- I’ve already left the redirect pointing to the file
login.php
;
- The archive
logout_status.php
must be in the same directory as index.php
(side-by-side);
You can download this project into mine Github/Lipespry/sopt-check-value-of-sessionlogout-without-update-to-page.
This, check every 5 seconds for example.
– Gabriel Elias
I deleted my comments as I formulated the answer. If it serves you, accept it as a solution for future members. If you lack something, you can comment on the reply that I will review.
– LipESprY