Session/Cookie Lifetime?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Syn
Forum Newbie
Posts: 3
Joined: Fri Oct 28, 2005 7:32 am

Session/Cookie Lifetime?

Post by Syn »

Hello!

Me and a few friends are developing a game that uses some simple PHP code to track what a user has completed in some various quests. Basically what someone can do is collect items from NPCs, give items to NPCs and take instructions. Simple stuff.

One problem we have been encountering is that the tasks that the user carries out is not being saved. After a few hours, all the users quest status, items etc is wiped from the cookie it should be saved to. I need a way to make this cookie last for a very long time (at least a year or two).

I will post the code of the main PHP script we have right now that controls all of the game interaction.

Code: Select all

<?
// start the session.
ini_set('session.cookie_lifetime',(3600*24*365));
session_start();

// Create Item and Session tasks if necessary
if(!isset($_SESSION["Items"])){ $_SESSION["Items"] = Array(); }
if(!isset($_SESSION["Tasks"])){ $_SESSION["Tasks"] = Array(); }
if(!isset($_SESSION["Counters"])){ $_SESSION["Counters"] = Array(); }

// Get the location of this file.
$Location = $_SERVER["PHP_SELF"];

// Collect all the Get variables (ie, all the arguments after the filename, such as char1.php?n=4&test=hithere).
import_request_variables("g", "Get");
// Collect all the Post variables (these come from form elements like text boxes that the user fills out).
import_request_variables("p", "Post");

//*
GiveItem() records an item in the session variable.
*/
function GiveItem($ItemName){ if((!isset($_SESSION["Items"][$ItemName])) || ($_SESSION["Items"][$ItemName] == 0)){$_SESSION["Items"][$ItemName] = 1;} }

/*
TakeItem() re-sets a cookie you've already set, taking away that item.  The cookie will look like:
ItemName=0
*/
function TakeItem($ItemName){ if(isset($_SESSION["Items"][$ItemName])){$_SESSION["Items"][$ItemName] = 0;} }

/*
HasItem() checks to see that the given item name exists in the items array, and is true if it's there.
*/
function HasItem($ItemName){
	if(isset($_SESSION["Items"][$ItemName])){
		if($_SESSION["Items"][$ItemName] == 1){
			return true;
		} else { return false; }
	} else { return false; }
}

/*
Give task puts a task in the task array.  Initial value of 1.  Finish task changes the value of that task to "done".
Checktask checks to see if the task is done.  Returns true if it's done, otherwise false.
*/
function GiveTask($TaskName){ if((!isset($_SESSION["Tasks"][$TaskName]))||($_SESSION["Tasks"][$TaskName] == "done")){$_SESSION["Tasks"][$TaskName] = 1;} }
function FinishTask($TaskName){ if(isset($_SESSION["Tasks"][$TaskName])){$_SESSION["Tasks"][$TaskName] = "done";} }
function CheckTask($TaskName){
	if(isset($_SESSION["Tasks"][$TaskName])){
		if($_SESSION["Tasks"][$TaskName] == "done"){
			return true;
		} else { return false; }
	} else { return false; }
}

/*
MakeCounter() adds a new counter to the list.  Initial value 1.
ChangeCounter() changes a counter's value, either up or down, by any amount.  $Dir should be "+" or "-", otherwise it'll fail.  $Amount is a number.
IncreaseCounter() increases a counter by any amount.
DecreaseCounter() decreases a counter by any amount.
IncrementCounter() increases a counter by one.
DecrementCounter() decreases a counter by one.
*/
function MakeCounter($CountName){ if(!isset($_SESSION["Counters"][$CountName])){$_SESSION["Counters"][$CountName] = 1;} }
function ChangeCounter($CountName, $Dir, $Amount){
	eval("\$_SESSION[\"Counters\"][\$CountName] $Dir = $Amount");
}
function IncreaseCounter($CountName, $Amount){ ChangeCounter($CountName, "+", $Amount); }
function DecreaseCounter($CountName, $Amount){ ChangeCounter($CountName, "-", $Amount); }
function IncrementCounter($CountName){ ChangeCounter($CountName, "+", 1); }
function DecrementCounter($CountName){ ChangeCounter($CountName, "-", 1); }
function CheckCounter($CountName){ if(isset($_SESSION["Counters"][$CountName])){ return $_SESSION["Counters"][$CountName]; } else {return "e"; } }



?>
You can, for the most part, ignore most of the body of the code. I'm just wondering if we need to use something other than this code below to store the session in a cookie that lasts a long time. I know it's creating sessions, but don't I want to create cookie sessions instead? This session as defined below (which is the very top part of the above code) expires after a couple hours.

Code: Select all

<?
// start the session.
ini_set('session.cookie_lifetime',(3600*24*365));
session_start();

// Create Item and Session tasks if necessary
if(!isset($_SESSION["Items"])){ $_SESSION["Items"] = Array(); }
if(!isset($_SESSION["Tasks"])){ $_SESSION["Tasks"] = Array(); }
if(!isset($_SESSION["Counters"])){ $_SESSION["Counters"] = Array(); }

FYI: I posted the entire code because lots of the code inside has the if(!isset) functions hardcoded right into it. If I were to change this code here, I would probably have to also change the inner code, right?

So basically, what my problem is is that the information is only being stored for a couple hours, when I need it to be stored for a very long time. Any suggestions?
Syn
Forum Newbie
Posts: 3
Joined: Fri Oct 28, 2005 7:32 am

Post by Syn »

Sorry for the double post. I asked a friend about my problem and he pointed me to this website: http://uk.php.net/setcookie
On that website, I found this code:

Code: Select all

<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
   foreach ($_COOKIE['cookie'] as $name => $value) {
       echo "$name : $value <br />\n";
   }
}
?>
Could I just use this method to set cookies for "Items", "Tasks" and "Counters?" I suppose my new, edited code would be:

Code: Select all

//Add in this new code, setting the cookies
setcookie("cookie[three]", "Items");
setcookie("cookie[two]", "Tasks");
setcookie("cookie[one]", "Counters");


// Create Item and Session tasks if necessary 
if(!isset($_COOKIE["Items"])){ $_COOKIE["Items"] = Array(); } 
if(!isset($_COOKIE["Tasks"])){ $_COOKIE["Tasks"] = Array(); } 
if(!isset($_COOKIE["Counters"])){ $_COOKIE["Counters"] = Array(); }
Then throughout the body of the code, I could just change all the '$_SESSION' arrays to '$_COOKIE'. Then, I suppose I could add in a time()+3600*24*365 parameter into each of the setcookie() functions to make them last a year.


Any thoughts or comments? I'm sorry, I'm pretty new to php. :P
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Ya, you could do that. I'd recommend though, that you don't rely on the contents of the cookie to get your game data. Its quite easy to change the contents of cookies, so if I wanted to, I could go into the 'Items' cookie and give myself the best gear in the game.

I'd recommend keeping your stuff in sessions, then on every page load, match up your database (or flat file if you're doing it that way) with the contents of the session. This will also allow people to play your game on different browser on different computers.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it sounds more like you may be running into the session system's lifetime limiters or your host's own session storage cleaning mechanism.. It may be of interest to use database sessions..
Syn
Forum Newbie
Posts: 3
Joined: Fri Oct 28, 2005 7:32 am

Post by Syn »

You both bring up good points that I have thought about slightly in the past. Alas, I have no idea how to link the sessions to a database. Any resources I could possibly take a look at? It looks like I'm going to have to do the database link.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

you can find a link to a thread with a possible solution for database sessions in the "Useful Posts" thread found in the PHP - Code board or linked to from my signature.
Post Reply