Professional Documents
Culture Documents
Creating a cookie
setcookie(name,value,expiration);
Eg, setcookie(fruit,banana,time()+3600);
The cookie is called fruit and has a value of
banana; it will expire 1 hr from now.
Eg. setcookie(username,jceddia,time()
+1800);
Accessing A Cookie
Once created,cookie values are automatically
available to PHP scripts as a variable having
the same name as the cookie.
Eg. echo the current user is $username;
Cookie examples
<?php
// set an individual cookie
$value = 'something from somewhere';
setcookie ("TestCookie", $value);
setcookie ("TestCookie", $value,time()+3600); /* expire
in 1 hour */
setcookie ("TestCookie", $value,time()+3600,
"/~rasmus/", ".example.com", 1);
?>
<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"]; /* old
style */
?>
Deleting a Cookie
Automatically deleted after expiration time
Can manually delete by setting negative
time
setcookie(username,,time()-3600);
Redirection
Once login data is captured/validated then want to go to a
new page.
Header(Location: URL);
header("Location:
http://sng.its.monash.edu.au:7777/p-6-2.html
");
Or header("Location:filename); if on same server
General technique:
Sessions
What if user disables cookies? Need to store data
on the server. This is done in session variables.
A session variable is a regular global variable that,
when registered as a session variable, keeps its
value on all pages that use PHP4 sessions.
To register a session variable:
assign a value to a variable that is to become a session
variable
$mysessvar = somevalue
and call
session_register(mysessvar").
Session cont.
A visitor accessing your web site is assigned an unique
id, the so-called session id. This is either stored in a
cookie on the user side or is propagated in the URL.
The session support allows you to register arbitrary
numbers of variables to be preserved across requests.
When a visitor accesses your site, PHP will check
automatically (if session.auto_start is set to 1) or on your
request (explicitly through session_start() or implicitly
through session_register()) whether a specific session id
has been sent with the request. If this is the case, the
prior saved environment is recreated.
All registered variables are serialized after the request
finishes. Registered variables which are undefined are
marked as being not defined. On subsequent accesses,
these are not defined by the session module unless the
user defines them later.
?>
Session Ids.
There are two methods to propagate a session id:
Cookies
URL parameter
The session module supports both methods. Cookies
are optimal, but since they are not reliable (clients are
not bound to accept them), we cannot rely on them. The
second method embeds the session id directly into
URLs.
PHP is capable of doing this transparently when
compiled with --enable-trans-sid. If you enable this
option, relative URIs will be changed to contain the
session id automatically. Alternatively, you can use the
constant SID which is defined, if the client did not send
the appropriate cookie. SID is either of the form
session_name=session_id or is an empty string.
Sids
The following example demonstrates how to register a
variable, and how to link correctly to another page using
SID.
Example 5. Counting the number of hits of a single user
<?php
if (!session_is_registered('count')) {
session_register('count');
$count = 1;
}
else {
$count++;
}
?>
Hello visitor, you have seen this page <?php echo $count; ?>
times.<p>;
Sids cont.
<?php
# the <?php echo SID?> (<?=SID?> can be used if
short tag is enabled)
# is necessary to preserve the session id
# in the case that the user has disabled cookies
?>
To continue, <A HREF="nextpage.php?<?php echo SID?>">click
here</A>
Session functions
Session_start()
All pages that uses PHP4 sessions must call
the function session_start() to tell the PHP4
engine to load session related information
into memory. The session_start() function
tries to find the session id in the cookie field
or the request parameters for the current
HTTP request. If it cannot find the session
id, a new session is created.
Session_register()
The first example (page1.php):
<?php
session_start();
$my_session_variable = "some value";
session_register("my_session_variable");
?>
//may also use $_SESSION[my_session_var'] =
somevalue;
Example 2 (page2.php):
<?php
session_start();
print "Value of 'my_session_variable':
$my_session_variable";
?>
Templates
Templates allow the separation of php code
from html
Useful on large sites where graphic designers
manipulate html and php programmers write
code
<HTML><HEAD>
<TITLE> Sample Template</TITLE></HEAD>
<BODY>
The answer to todays question is {ANSWER}.
</BODY></HTML>
To Use Templates - do
Template Example.
Assume that there is a template in the
/home/mydir/mytemplates/ named MyTemplate.tpl
that has some text that reads something like this:
Congratulations! You won a new {some_color} Book!
"{some_color}" has curly braces around it. The curly
braces indicate that some_color is a template variable.
A PHP script that will load the template, insert the
value of the PHP variable $my_color where the
{some_color} template variable tag is, and then
output the new text. If $my_color happens to be set to
"blue", the final output should look like:
Congratulations! You won a new blue Book!
Nested Templates
A feature of the parse() function is that the MyOutput
handle that it created is actually a template variable, just as
{some_color} is a template variable. So if you have
another template with a {MyOutput} tag, when you parse
that second template, all of the {MyOutput} tags will be
replaced with the parsed text from MyOutput. This lets you
embed the text of one template file into another template.
So, we could have another template called wholePage.tpl
that contains the text:
Sorry you didn't win. But if you had won, we would have told you:
{MyOutput}
Example
<?php
$t = new Template("/home/mydir/mytemplates/");
$t->set_file(array(
"mainpage" => "mainpage.tpl",
"each_element" => "each_element.tpl"));
reset($myArray);
while (list($elementName, $elementValue) = each($myArray)) {
// Set 'value' and 'name' to each element's value and name:
$t->set_var("name",$elementName);
$t->set_var("value",$elementValue);
// Append copies of each_element:
$t->parse("array_elements","each_element",true);
}
$t->pparse("output","mainpage");
?>
Example cont.
This example uses two templates, mainpage.tpl and each_element.tpl.
The mainpage.tpl template could look something like this:
<HTML>
Here is the array:
<TABLE>
{array_elements}
</TABLE>
</HTML>
The {array_elements} tag above will be replaced with copies of
each_element.tpl, which is repeated for each element of the array
($myArray). The
each_element.tpl template might look like this:
<TR> <TD>{name}: {value}</TD> </TR>
The result is a formatted table of the elements of $myArray.
Example - Std.tpl
<HTML>
<HEAD>
<TITLE>{title}</TITLE>
</HEAD>
<BODY>
<TABLE CELLPADDING="10">
<TR>
<TD COLSPAN="2" ALIGN="LEFT">{header}</TD>
</TR>
<TR>
<TD VALIGN="TOP" ALIGN="LEFT">{leftnav}</TD>
<TD VALIGN="TOP" ALIGN="LEFT">{content}</TD>
</TR>
</TABLE> </BODY> </HTML>
Example - header.tpl
<TABLE CELLPADDING="5" BORDER="1"
WIDTH="600">
<TR>
<TD>
<FONT SIZE="6"><B>The Generic Web Site
</B></FONT>
<BR>
</TR>
</TABLE>
Example - leftnav.tpl
<TABLE CELLPADDING="5" BORDER="1"
WIDTH="100">
<TR>
<TD>
<A HREF="index.php"><BR>Home<BR><BR>
<A HREF="function1.php">Function 1<BR><BR>
<A HREF="function2.php">Function 2<BR><BR>
<A HREF="logout.php"><BR>Logout<BR>
</TR>
</TABLE>
Example - index.tpl
<FONT SIZE="7">Welcome to the <BR>{title}!</FONT>
<BR>
<BR>
This is where you'll find information about absolutely nothing.
We're so sure you won't find anything of interest here, we'll
pay you if you can show us we're wrong.
Example - index.php
<?php
include 'template.inc';
$tpl = new Template('.');
//assume the templates are in the current directory
$tpl->set_file(array('std' =>'std.tpl',
'header' =>'header.tpl',
'leftnav'=>'leftnav.tpl',
'content'=>'index.tpl'));
$tpl->set_var('title', 'Generic Web Site');
$tpl->parse('header', 'header');
$tpl->parse('leftnav', 'leftnav');
$tpl->parse('content', 'content');
$tpl->parse('DUMMY', 'std');
$tpl->p('DUMMY');
?>