This should do the job (hope so anyway).
This should go at the top of your pages. A better option would be to make a page called cookie.php, put the “cookie.php” code below in it and include it on every page.
include ("cookie.php");
Note: that this should be called before anything is sent to the browser.
I set a “test” time of 10 seconds. Change it to 3600 when testing is done. The constant NUM_HOURS is set at 1 at the top of the page. Change as needed.
Also note, this is a stand alone option that calls the function from the same page, which should work if all pages are within same directory as index.php.
IF however you are using multiple directories where index.php is not located, then you should:
- Remove the part that CALLS the function and put it on each page adjusting the path to index.php accordingly.
- Remove the place where the path to the index.php is set to variable $SiteURL.
How function is called(bottom of cookie.php)
if (!isset($_COOKIE[COOKIE_KEY])){
cookieLogin($SiteURL);
}
cookie.php
<?php
//Cookie.php
///////////////////////////////
/// Cookie Settings
const COOKIE_KEY = 'HomePageCookie';
const NUM_HOURS = 1; // number of hours key is valid
///////////////////////////////
/// Path to redirect page
$SiteURL = "index.php";
///////////////////////////////
function cookieLogin($SiteURL) {
// load cookie
if (isset($_COOKIE[COOKIE_KEY])) {
$parts = explode('|', $_COOKIE[COOKIE_KEY]);
$Token = $parts[0];
$sessionKey = $parts[1];
} else {
$Token = $sessionKey = false;
}
// No cookie at all
if (empty($sessionKey) || empty($Token)) {
/////////////////////////////////
function generateKey() {
// get the largest 999999999 we can rand to.
$max = (int)str_pad('', strlen(mt_getrandmax()) - 1, 9);
$min = (int)str_pad('1', strlen($max), 0, STR_PAD_RIGHT);
$key = '';
while (strlen($key) < 39) {
$key .= mt_rand($min, $max);
}
return substr($key, 0, 39);
}
/////////////////////////////////
function generateToken() {
// get the largest 999999999 we can rand to.
$max = (int)str_pad('', strlen(mt_getrandmax()) - 1, 9);
$min = (int)str_pad('1', strlen($max), 0, STR_PAD_RIGHT);
$key = '';
while (strlen($key) < 4) {
$key .= mt_rand($min, $max);
}
return substr($key, 0, 4);
}
/////////////////////////////////
$key = generateKey();
$Token = generateToken();
// Store key in cookie
setcookie(COOKIE_KEY,
"$Token|$key",
//FOR TESTING set time for 10 seconds
time() + (10 * NUM_HOURS));
//ELSE USE 3600
//time() + (3600 * NUM_HOURS));
header("location: $SiteURL");
exit;
}
}
if (!isset($_COOKIE[COOKIE_KEY])){
cookieLogin($SiteURL);
}
?>
You may not even need all that’s here as I was using part of this in another program, saving keys and tokens in DB for match but it should do the job.