Jump to content

Need help coding cookies


hazade

Recommended Posts

Ok guys, first off i'm fairly new to PHP so this might be a simple thing but I am having trouble figuring it out.

 

Basically, on the main page of my site I have a form that submits a variable ($ts) to another page on the site. The second page takes that variable and uses it to display data. What I am trying to do is set it up so that the page remembers the last 5 strings recieved from the $ts variable and display them in a "recently viewed" column.  I am assuming I have to set up an array in the cookie to remember the last 5 variables but I am unsure how to set it up/retrieve the data from the cookie.

 

Any help would be greatly appreciated.

 

Thanks

Link to comment
Share on other sites

Use:

//setcookie('cookiename')

//setcookie('cookiename[index]')

//cookie names can be arrays in setcookies function

setcookie("recentItems[$currentItemIndex]");

 

To read Use:

foreach ($_COOKIE['recentItems'] as $cookie){

    //use $cookie here to display wherever you want

}

Link to comment
Share on other sites

Use sessions for data that you want to persist between pages in an individual visit to a site.

 

Use cookies (or a database) for data you want to persist between browser visits to a site.

 

In your case, I'd probably go with a database-only approach.  Here's why.

 

You've already said you want the data to persist between browser sessions, so we already know you'll need to use a database or cookies to store data long term.  For this I'd use the database for two reasons.  The first is that users can turn cookies off, thus disabling this feature of your website.  The second is that cookies have an expiration so eventually they'll disappear on the user's machine anyway.

 

The next task is to deal with how you'll access this data in your scripts.  Sessions are very convenient and easy to access, but here's the catch.  As soon as the user closes the browser or the session ends due to inactivity, the session is over and all data contained within is lost.  There is no way, that I'm aware of, to register a function to run at the end of a session.  This means that any data in the session you wish to save long-term, be it in a cookie, server-file, database, etc., will need to be saved every time that data changes.  So every time you update a value in the session, you'll be saving it to the database (or a cookie) as well.

 

So in my opinion you might as well scratch sessions as a solution to your problem as that will just introduce extra overhead.  Write a nice utility class to interface with the database (or cookies) that allows you to easily store and retrieve data and it'll be just as easy to use as sessions but the data will last between browser instances.

 

My $.02.

Link to comment
Share on other sites

Thanks for the reply. I still think cookies will be the best way to accomplish this. The data does not need to be remembered long term, 1 week at the most. The only reason I am against going the database route is because wouldn't that require the users to log in to some kind of account to work? I would like this function to work for users without logging in.

 

The information isnt critical to the site so if they disable cookies it would not be a big deal, and the 1 week time frame would be plenty so the cookie expiration could last for that week. I'm just having trouble figuring out how to put this information into an array in a cookie without overwriting the previous entry. I would like it to start overwriting the oldest entry after the 5 entries are filled up and then recall the entries from newest to oldest.

Link to comment
Share on other sites

I'd wrap this up in a nice little class to make it easier to use, but here's the basics.

 

You need to store the current data into an array.  We already know this array will have a maximum of 5 elements, so you can arbitrarily decide small indexes indicate older data and bigger indexes indicate newer data; i.e. $Data[0] is the oldest recorded visit and $Data[4] is the newest visit.

 

Define a function that allows you to add a data to the array.  You append the data as the last array element, remove the first array element, and then re-order the indexes of the array back to 0 through 4.

 

Define a function that allows you to save the array to a cookie by serializing it.

 

Define a function that allows you to load the array from the cookie by unserializing it.

 

Let us know if you get stuck.

Link to comment
Share on other sites

OK, I finally got somewhere here and have it kind of functional... to set the cookie I used this:

 

<?php

error_reporting (E_ALL ^ E_WARNING ^ E_NOTICE);

// Module to log current page

// Get current URL
$URL = $tsym;

// Create MD5 signature of current URL
$md5sig = md5($URL);

// Set cookie of current url
setcookie ("history[" . $md5sig . "][url]", $URL, time() + (60*60));
setcookie ("history[" . $md5sig . "][count]", intval($_COOKIE['history'][$md5sig]['count']) + 1, time() + (60*60));

function iif($expression, $returntrue, $returnfalse = '') {
return ($expression ? $returntrue : $returnfalse);
}
?>

 

and then to retrieve the information, I used:

 

<?php

if (!is_array($_COOKIE['history'])) {
echo "<font size=2><br>N/A";
} else { 

foreach ($_COOKIE['history'] AS $entry) {

echo $entry['url']; 

}
} ?>

 

Now this works for the most part, but I'm running into 2 little problems with the code. The first problem is I would like the newest entries to be displayed first, rather than last. And the second problem is stopping after a certain amount of entries (say, 5), moving the whole array down to erase the oldest and enter the newest. Any thoughts?

Link to comment
Share on other sites

  • 2 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.