Below are two functions.
The first is to set a cookie. This function is called on any product page on my website.
function setcookie() {
$entry_id = $this->EE->TMPL->fetch_param('entry_id');
if (isset($_COOKIE['recently_viewed'])) {
$currentSession = unserialize($_COOKIE['recently_viewed']);
if (!in_array($entry_id, $currentSession)) {
if (count($currentSession) > 5) {
unset($currentSession[0]);
}
$currentSession[] = $entry_id;
} else {}
$currentSession = serialize($currentSession);
setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');
} else {
$recently_viewed[] = $entry_id;
$currentSession = serialize($recently_viewed);
setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');
}
}
The second function retrieves the IDs in the cookie array and outputs them.
function recently_viewed() {
$tagdata = $this->EE->TMPL->tagdata;
if ( array_key_exists('recently_viewed', $_COOKIE) ) {
$recent = unserialize($_COOKIE['recently_viewed']);
} else {
$recent = NULL;
}
if ($recent) {
$entry_ids = implode('|', $recent);
} else {
$entry_ids = NULL;
}
$data['entry_ids'] = $entry_ids;
$variables = array();
$variables[] = $data;
return $this->EE->TMPL->parse_variables($tagdata, $variables);
}
The code is built for the content management system Expression Engine. If you don't know 'codeigniter' code, just ignore those bits and take a look at the straight PHP if possible.
Can anyone tell me if there is any way to speed the functions up?
The first function, setcookie
, is basically checking to see if a cookie exists. If it does, it checks if the current entry id
is in the array already. If it's not, then it checks if there are more than 5 items in the array. If there is, it deletes the first one and adds the new entry id
. If no cookie exists, it creates a new cookie and adds the entry id
.
The second function (recently viewed) is checks the cookie, converts it to a string with pipelines between entry ids
, then outputs this string.