-
Start with a new Simple page template from the PHP templates
-
Create some global variables at the top of the PHP source code
global $cookie1, $cookie_msg;
-
Replace:
// Retrieve the task (default to "default")
if ($pf_task == 'default')
generic();
with the following:
// run the specified task
switch($pf_task)
{
case 'default':
generic();
break;
case 'cookie_value':
cookie_value();
break;
case 'retrieve':
retrieve();
break;
case 'clear':
clear();
break;
}
-
Copy the cookie_value function and paste it below the generic function
function cookie_value()
{
// Make all global variables available here
foreach($GLOBALS as $arraykey=>$arrayvalue)
{
if($arraykey[0]!='_' && $arraykey != 'GLOBALS')
global $$arraykey;
}
//get value from the form
$cookie1 = $_POST["cookie1"];
//set the cookie to value from the form. This cookie will expire in one hour.
setcookie("cookie1",$cookie1, time()+3600);
//write the MainSeg segment
wrtseg('MainSeg');
}
-
Copy the retrieve function and paste it below the generic function.
function retrieve()
{
// Make all global variables available here
foreach($GLOBALS as $arraykey=>$arrayvalue)
{
if($arraykey[0]!='_' && $arraykey != 'GLOBALS')
global $$arraykey;
}
//if we have a cookie set with a value display a message
if(isset($_COOKIE['cookie1']))
{
$msg = "You set\"<strong>";
$msg2 = "</strong>\" as the cookie contents";
$cookie_msg = $msg . $_COOKIE["cookie1"] . $msg2;
}
else
{
$msg = "";
$msg2 = "";
$cookie_msg = "<strong><span style=\"color:red;\">
Please set the cookie with a value</span></strong>";
}
wrtseg('MainSeg');
}
Now add the clear function right after the retrieve function.
function clear()
{
// Make all global variables available here
foreach($GLOBALS as $arraykey=>$arrayvalue)
{
if($arraykey[0]!='_' && $arraykey != 'GLOBALS')
global $$arraykey;
}
//this will set the cookie to a time in the past and it will be destroyed
setcookie("cookie1","",time() - 3600);
wrtseg('MainSeg');
}
-
In the HTML MainSeg segment create a table and form to set and retrieve the cookie value
<table>
<tr>
<td><strong>Enter a value for the cookie</strong></td>
</tr>
<tr>
<td>
<form action="cookies.php" method="POST">
<input type="hidden" name="task" value="cookie_value">
<input type="text" size="30" name="cookie1" value="$cookie1">
<input type="submit" value="Set Cookie">
</form>
</td>
</tr>
</table>
<br>
<table>
<tr>
<td><strong>Retrieve the value of the cookie</strong</td>
<td><a href="$pf_scriptname?task=retrieve">Click here</a></td>
<td>$cookie_msg</td>
</tr>
<tr><td colspan="3"><td> </tr>
<tr>
<td><strong>Clear the value of the cookie</strong></td>
<td><a href="$pf_scriptname?task=clear">Click here</a></td>
<td></td>
</tr>
</table>
-
Compile and run your program