Use this on login or on the method when you are creating the cookies
setcookie("user", "User Name", time()+5*60);
The syntax for setcookie() method is-
setcookie(name, value, expire, path, domain);
where expire
is the time when the cookie will expire, you can give this time in relative to the current time by adding few more second to the value returned by time()
method, name
is the name of cookie, by which the value will be accessed, and the value
is the value. See the documentation here.
And on other page check with-
if (!isset($_COOKIE["user"]))
header("Location:timeout.php");
The methods setcookie() and header() should be called before the output is sent. The alternative(a little tricky) of header() you can do with -
if (!isset($_COOKIE["user"]))
echo '<script type="text/javascript">
document.location = "timeout.php";
</script>';
This will redirect the page using javascript.
Content of index.php-
<?php
session_start();
if(!isset($_SESSION['visited']))
{
$_SESSION['visited'] = time();
setcookie("user", "User Name", time()+5*60);
}
else
{
if(!isset($_COOKIE["user"]))
header("Location:timeout.php");
}
?>
<html><body>This is my page</body></html>
Content of timeout.php-
<?php
session_start();
unset($_SESSION['visited']);
?>
<html><body>Timeout, again go to <a href="index.php">main page</a></body></html>