1

I'm playing with PHP and am looking to achieve the following (I know this is possible with third party plug-ins, but I want to build this on my own as practice):

  1. Store the history of all URLs the user visits within my (Joomla driven) site in a cookie.
  2. Send an array of values (other user information including the URL history) to a source (file or database) when the user logs out. I have not tackled item two yet, but an answer or a good pointer would be appreciated.

The PHP Code I've created so far:

$user   = JFactory::getUser();
$helper = JUserHelper::getUserGroups($user->id);

if(!isset($_COOKIE['pagehistory'])){
    setcookie('pagehistory',$_SERVER['REQUEST_URI'].'|');
}
else {
    $_COOKIE['pagehistory'] .= $_SERVER['REQUEST_URI'].'|';
}

// debug: destroy cookie
//setcookie ("pagehistory", "", time() - 3600);

$group  = "";
foreach ($helper as $value) {
    $group .= $value."|";
}

$userinfo = array(
'id'        => $user->id,
'username'  => $user->username,
'realname'  => $user->name,
'group'     => $group,
'url'       => $_SERVER['REQUEST_URI'],
'history'   => $_COOKIE['pagehistory'],
);

The issue I'm having is with the 'pagehistory' cookie. When I do a test using the console, I seem to get only the first URL and the ever-overriding second, but no more.

Example:

Nav to URL 1: '/' //(root)
Nav to URL 2: '/news'
Nav to URL 3: '/tutorials'

Results of cookie code:

Round 1 : '/'
Round 2 : '/|/news' // '|' being the delimiter
Round 3 : '/|/tutorials' // instead of '/|/news|/tutorials'

What am I doing wrong?

Expedito
  • 7,771
  • 5
  • 30
  • 43
brooklynsweb
  • 817
  • 3
  • 12
  • 26

1 Answers1

0

cookies are created by setcookie function. Change the else to following and see if this fixes it:

else {
    $tmp = $_COOKIE['pagehistory'] . $_SERVER['REQUEST_URI'] . '|';
    setcookie('pagehistory', $tmp);
}
dhavald
  • 524
  • 4
  • 12
  • This solution worked, but I'm confused regarding the technique. I was under the impression that 'setcookie' is used to create a cookie with the initial value. But if my goal is to continuously update that same cookie when a user hits a new page, I have to set it yet again? Would that not create two cookies, would the setting a cookie with the same name of a cookie that already exist just overwrite the original? – brooklynsweb May 09 '13 at 20:02
  • @brooklynsweb yes, it will overwrite if you specify same domain or path params, which in your case are same always. Take a look at [this](http://stackoverflow.com/q/6487564/1940041) – dhavald May 09 '13 at 20:25
  • Jsut save the previously saved cookie into database and then overwrite . – Mohd Sadiq Apr 10 '15 at 12:47