3. Server-Side Scripting
A "skrip" adalah koleksi program atau urutan
arahan yang ditafsirkan atau dijalankan oleh
program lain dan bukannya oleh pemproses
komputer.
Server-side / Server-side
Client-side / Pelanggan-side
Dalam server-side scripting, (seperti PHP, ASP)
skrip diproses oleh pelayan Like: Apache,
ColdFusion, ISAPI dan Microsoft IIS pada
Windows.
4. Server-Side Scripting – Continued
Advantages of Server-Side Scripting
Dynamic content.
Computational capability.
Database and file system access.
Network access (from the server only).
Built-in libraries and functions.
Known platform for execution (as opposed to
client-side, where the platform is uncontrolled.)
Security improvements
5. Introduction to PHP
• PHP stands for PHP: Hypertext Preprocessor
• Developed by Rasmus Lerdorf in 1994
• It is a powerful server-side scripting language
for creating dynamic and interactive websites.
• It is an open source software, which is widely
used and free to download and use (PHP is
FREE to download from the official PHP
resource: www.php.net).
• It is an efficient alternative to competitors such
as Microsoft's ASP.
6. Introduction to PHP
• PHP is perfectly suited for Web development
and can be embedded directly into the HTML
code.
• The PHP syntax is very similar to JavaScript,
Perl and C.
• PHP is often used together with Apache (web
server) on various operating systems. It also
supports ISAPI and can be used with
Microsoft's IIS on Windows.
• PHP supports many databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL,
7. Introduction to PHP
• What is a PHPFile?
• PHP files have a file extension of ".php",
".php3", or ".phtml"
• PHP files can contain text, HTML tags and
scripts
• PHP files are returned to the browser as plain
HTML
8. Introduction to PHP
What you need to develop PHPApplication:
• Install Apache (or IIS) on your own server,
install PHP, and MySQL
• OR
• Install Wampserver2 (a bundle of PHP, Apache,
and MySql server) on your own server/machine
9. PHP Installation Downloads
Free Download
PHP: http://www.php.net/downloads.php
MySQL Database: http://www.mysql.com/downloads/index.html
Apache Server: http://httpd.apache.org/download.cgi
• How to install and configure apache
• Here is a link to a good tutorial from PHP.net on how to install PHP5:
http://www.php.net/manual/en/install.php
10. How PHP is Processed
• When a PHP document is requested of a
server, the server will send the document first
to a PHP processor
• Two modes of operation
– Copy mode in which plain HTML is copied to the
output
– Interpret mode in which PHP code is interpreted
and the output from that code sent to output
– The client never sees PHP code, only the output
produced by the code
11. Basic PHPSyntax
• PHP statements are terminated with semicolons ;
• Curly braces, { } are used to create compound
statements
• Variables cannot be defined in a compound statement
unless it is the body of a function
• PHP has typical scripting language characteristics
– Dynamic typing, un-typed variables
– Associative arrays
– Pattern matching
– Extensive libraries
• Primitives, Operations, Expressions
– Four scalar types: boolean, integer, double, string
– Two compound types: array, object
– Two special types: resource and NULL
12. Basic PHPSyntax
• A PHP scripting block always starts with <?php and
ends with ?>
<?php ……………. ?>
– Other options are:
1. <? ……………… ?>
2. <script> ... </script>
• There are three basic statements to output text with
PHP: echo, print, and printf. Example:
echo 'This is a <b>test</b>!';
• Comments:
– #
– //
– /* . . . * /
13. Basic PHPSyntax
Inserting external files:
PHP menyediakan empat fungsi yang
membolehkan anda untuk memasukkan
kod dari fail luaran : include() or require()
include_once() or require_once()
functions.
• E.g.
include("table2.php");
– Includedfiles start incopymode
14. Basic PHPSyntax
Example 1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <title>Simple PHP Example</title>
<body>
<?php
echo "Hello Class of 2011. This is my first PHP Script";
echo "<br />";
print "<b><i>What have you learnt and how many friends have you
made?</i></b>";
echo "<br /><a href='PHP I-BSIC.ppt'>PHP BASIC</a>";
?>
</body>
</html>
15. PHPVariables
• Variables are used for storing
values, such as numbers,
strings or function results, so
that they can be used many
times in a script.
• All variables in PHP start with a
$ sign symbol.
• Variables are assigned using
the assignment operator "="
• Variable names are case
sensitive in PHP: $name is not
the same as $NAME or $Name.
• In PHP a variable does not
need to be declared before
being set.
Example:
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
$var1 = 'PHP'; // Assigns a value of 'PHP' to
$var1
$var2 = 5; // Assigns a value of 5 to $var2
$var3 = $var2 + 1; // Assigns a value of 6 to
$var3
$var2 = $var1; // Assigns a value of 'PHP' to $var2
echo $var1; // Outputs 'PHP‘
echo "<br/>";
echo $var2; // Outputs 'PHP'
echo "<br/>";
echo $var3; // Outputs '6'
echo "<br/>";
echo $var1 . ' rules!'; // Outputs 'PHP rules!'
echo "$var1 rules!"; // Outputs 'PHP rules!'
echo '$var1 rules!'; // Outputs '$var1 rules!‘
?>
16. Variable Naming Rules
A variable name must start with a letter or an
underscore "_"
A variable name can only contain alpha-numeric
characters and underscores (a-z, A-Z, 0-9, and _
)
If variable name is more than one word, it should
be separated with an underscore e.g.
($my_string), or with capitalization ($myString)
17. Variable Scope and Lifetime
The scope of a variable
defined within a function
is local to that function.
A variable defined in the
main body of code has a
global scope.
If a function needs to use
a variable that is defined
in the main body of the
program, it must reference
it using the "global"
• Example:
<?php
function mul()
{
global $start;
print "<tr>";
for ($num=1; $num <= 10; $num++ )
{
$cell = $num * $start;
print "<td> " . $cell . " </td>";
}
print "</tr>";
}
$start = 0;
print "<table border=1
cellpadding=3>";
while ( $start <=10 )
{
mul();
$start++;
}
print "</table>";
?>
18. Strings in PHP
• a string is a sequence of letters, symbols, characters and arithmetic values or
combination of all tied together in single or double quotes.
• String literals are enclosed in single or double quotes
• Example:
<?php
$sum = 20;
echo 'the sum is: $sum';
echo "<br />";
echo "the sum is: $sum";
echo "<br />";
echo '<input type="text" name="first_name" id="first_name">';
?>
– Double quoted strings have escape sequences (such as /n or /r) interpreted
and variables interpolated (substituted)
– Single quoted strings have neither escape sequence interpretation nor variable
interpolation
– A literal $ sign in a double quoted string must be escaped with a backslash,
– Double-quoted strings can cover multiple lines
19. Escaping quotes with in quotes
Example 1:
<?php
$str = ""This is a PHP string examples quotes"";
echo $str;
?>
Example 2
<?php
$str = 'It's a nice day today.';
echo $str;
?>
20. The Assignment Operator
The Assignment operator is the most widely used and well known of all the
operators in PHP. You use it every time you create a variable. The
"="(equal to) sign is used, and what it does is it takes the expression from
the right and places it into the operand on the left. It is simple.
In this example we use the assignment operator(=) to place a value of 8
into the variable:
<?php
$var1 = 8;
?>
We can also combine operators together to produce expression results that
are set into our variables as value. We demonstrate this in the next few
lessons quite well. Let us continue on.
22. String Operators
Use a dot to concatenate two strings:
e.g.
$firstname = ‘Rob’;
$surname = ‘Tuley’;
// displays ‘Rob Tuley’
echo $firstname.’ ‘.$surname;
23. Arithmetic Operators
Example Name Result
$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.
25. Combining Operators
Note that you can combine operators, for
example use =, + and / in one expression:
$a = 4;
$b = 2;
$c = $a + $b + ($a/$b);
// $c has value 4+2+(4/2) = 8
Brackets help group operators.
26. Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Gtr than or equal to TRUE if $a is greater than or equal to $b.
27. Comparisons
Comparison expressions return a value of
TRUE (or ‘1’) or FALSE (or ‘0’).
e.g.
$a = 10;
$b = 13;
// result is true (‘1’)
echo $a < $b;
28. Incrementing/Decrementing
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
29. Logical Operators
Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
!$a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
30. Finally, a tricky one!
A single ? is the ternary operator.
(expr) ? if_expr_true : if_expr_false;
A test expression evaluates to TRUE or
FALSE.
TRUE gives first result (before colon)
FALSE gives second result (after colon)
31. Ternary Operator example
<?php
$a = 10;
$b = 13;
echo $a<$b ? ‘a smaller’:‘b smaller’;
// string ‘a smaller’ is echoed
// to the browser..
?>
32. The Concatenation Operator
• The concatenation operator (.) is used to put
two string values together.
• Example:
<?php
$txt1="Hello Everyone,";
$txt2="1234 is Dan’s home address";
echo $txt1.$txt2;
?>
33. Constants in PHP
Constants are named values whose values cannot be changed. When you create a
constant you should use all capital letters and underscores separating words to let
yourself and others know they are constants. A dollar sign is not needed in front of
the name when creating constants. We use the define() function in PHP to create
them.
Here is how we create a constant, and use true on the end to make it not worry about
letter casing:
Output:
The person that created this web page is named Adam Khoury.
<?php
// define(constant_name, value, case_sensitive=true);
define("AUTHOR_NAME", "Adam Khoury", true);
echo "The person that created this web page is named " . AUTHOR_NAME . ".";
?>
34. Control Structure
Control structures are the building blocks of
any programming language. PHP provides all
the control structures that you may have
encountered anywhere. The syntax is the
same as C or Perl.
Making computers think has always been the
goal of the computer architect and the
programmer. Using control structures
computers can make simple decisions and
when programmed cleverly they can do some
complex things.
35. Conditional Statements
1. The If...Else
Statement
Syntax
if (co nditio n) co de to be
e xe cute d if co nditio n is
true ;
else co de to be e xe cute d if
co nditio n is false ;
<?php
$d=date("D");
if ($d=="Fri") echo "Have a
nice weekend!";
If more than one line should
be executed if a
condition is true/false,
the lines should be
enclosed within curly
braces:
<?php
$d=date("D");
if ($d=="Fri")
{ echo "Hello!<br />";
echo "Have a nice
weekend!";
echo "See you on
36. Conditional Statements
2.The ElseIf Statement
• If you want to execute some
code if one of several
conditions is true use the
elseif statement
Syntax
if (co nditio n) co de to be
e xe cute d if co nditio n is
true ;
elseif (co nditio n) co de to
be e xe cute d if co nditio n
is true ;
<html><head> <title>good ......</title>
</head>
<body>
<?php
$hour= date("H");
if ($hour<= 11) {
echo "good morning my friend"; }
elseif ($hour> 11 && $hour< 18) {
echo "good afternoon my friend"; }
else { echo "good evening my
friend"; }
?>
</body></html>
37. PHPSwitch Statement
• If you want to select one of many
blocks of code to be executed, use
the Switch statement.
• The switch statement is used to
avoid long blocks of if..elseif..else
code.
Syntax
switch (e xpre ssio n)
{
case labe l1 : co de to be e xe cute d if
e xpre ssio n = labe l1 ;
break;
case labe l2: co de to be e xe cute d if
e xpre ssio n = labe l2;
break;
default: co de to be e xe cute d if
e xpre ssio n is diffe re nt fro m bo th
switch ($textcolor)
{
case "black":
echo "I'm black";
break;
case "blue":
echo "I'm blue";
break;
case "red":
echo "I'm red";
break;
default: // It must be
something else
echo "too bad!!, I'm
something else";
}
38. PHPLooping
• Looping statements in PHP are used to
execute the same block of code a specified
number of times.
• In PHP we have the following looping
statements:
– while - loops through a block of code if and as
long as a specified condition is true
– do...while - loops through a block of code once,
and then repeats the loop as long as a special
condition is true
– for- loops through a block of code a specified
number of times
– foreach - loops through a block of code for each
39. The while Statement
Syntax
while (condition)
{
// statements
}
Example
<html> <head> <title>Let us count !!!
</title></head>
<body>
<?php
$limit = 10;
echo "<h2> Let us count from 1 to $limit
</h2><br />";
$count = 1;
while ($count <= $limit)
{
echo "counting $count of $limit <br>";
$count++;
}
?>
40. The do...while Statement
• The do...while
statement will
execute a block of
code at least once -
it then will repeat the
loop as long as a
condition is true.
Syntax
• do { co de to be
e xe cute d; } while
(co nditio n);
Example
<html> <body>
<?php
$i=0;
do { $i++; echo "The number
is " . $i . "<br />"; }
while ($i<5);
?>
</body> </html>
41. The forStatement
• It is used when you know how many
times you want to execute a statement
or a list of statements.
Syntax
• for (init; co nd; incr) { co de to be
e xe cute d; } Parameters:
• init: Is mostly used to set a counter,
but can be any code to be executed
once at the beginning of the loop
statement.
• cond: Is evaluated at beginning of
each loop iteration. If the condition
evaluates to TRUE, the loop continues
and the code executes. If it evaluates
to FALSE, the execution of the loop
ends.
• incr: Is mostly used to increment a
Example
<html> <body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!
<br />";
}
?>
</body> </html>
42. The foreach Statement
• The foreach statement is
used to loop through arrays.
• For every loop, the value of
the current array element is
assigned to $value (and the
array pointer is moved by
one) - so on the next loop,
you'll be looking at the next
element.
Syntax
• foreach (array as value )
{ co de to be e xe cute d; }
Example
<html> <body>
<?php
$arr=array("one", "two",
"three");
foreach ($arr as $value) {
echo "Value: " . $value .
"<br />";
}
?>
</body> </html>
43. Object and Classes in PHP
PHP, like most modern programming languages (C++, Java, Perl, JavaScript, etc.),
supports the creation of objects.
Creating an object requires you to first define an object class (containing variables
and/or function definitions) and then using the “new” keyword to create an instance of
the object class. (Note that the object must be defined before you instantiate it.)
<?php
// Assume that the "Person" object has been previously defined. . .
$x = new Person; // creates an instance of the Person class (*no* quotes)
// The object type need not be "hardcoded" into the declaration.
$object_type = 'Person';
$y = new $object_type; // equivalent to $y = new Person;
$z = new Vehicle('Jaguar','green'); // creating an object and passing
// arguments to its constructor
44. Defining (declaring) a class
Use the “class” keyword which includes the class name (case-insensitive, but
otherwise following the rules for PHP identifiers). Note: The name “stdClass” is
reserved for use by the PHP interpreter.
<?php
class Person
{
var $name;
function set_name($new_name) {
$name = $this -> new_name;
}
function get_name() {
return $this -> name;
}
}
Use the “$this” variable when accessing properties and functions of the current
object. Inside a method this variable contains a reference to the object on which
the method was called.
45. Declaring a class (cont.)
Properties and functions can be declared as “public” (accessible outside the
object’s scope), “private” (accessible only by methods within the same class), or
“protected” (accessible only through the class methods and the class methods of
classes inheriting from the class.
Note that unless a property is going to be explicitly declared as public, private, or
protected, it need not be declared before being used (like regular PHP variables).
<?php
class Person
{
protected $name;
protected $age;
function set_name($new_name) {
$name = $this -> new_name;
}
function get_name() {
return $this -> name;
}
}
46. Declaring a class (cont.)
Classes can also have their own constants defined (using the “const” keyword), can
have their own static properties and functions (using the keyword “static” before
“var” or “function”), and can also can constructors and destructors (see below).
Static properties and functions are accessed (see below) using a different format
than usual for objects, and static functions cannot access the objects properties
(i.e. the variable $this is not defined inside of a static function).
<?php
class HTMLtable {
static function start() {
echo "<table> n";
}
static function end() {
echo "</table> n";
}
}
HTMLtable::start();
?>
47. Accessing properties and
methods
Once you have an object, you access methods and properties (variables) of the
object using the -> notation.
<?php
$me = new Person;
$me -> set_name('Russ');
$me -> print_name();
$name = $me -> get_name();
echo $me -> get_name();
$age = 36;
$me -> set_age($age);
?>
48. PHP Function
In php a function is a predefined set of
commands that are carried out when the
function is called.
The real power of PHP comes from its
functions.
PHP has more than 700 built-in or predefine
functions for you to use.
Complete php string reference
You can write your own functions
50. Using Built-in Function
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
$a = abs(-.43);
$b = sqrt(16);
$c = round(12.3);
print "The absolute value of -.43 is " . $a . "<br />";
print "The square root of 16 is " . $b . "<br />";
print "12.3 rounded is " . $c . " and 12.5 rounded is " . round(12.5);
?>
</body>
</html>
51. Using Built-in Function
Examples: Inserting external files:
PHP provides four functions that enable you to insert code
from external files: include() or require() include_once() or
require_once() functions.
A sample include file called add.php
<html> <body>
<?php
function add( $x, $y ) {
return $x + $y; }
?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body> </html>
Using the include function
<?php
include('add.php');
echo add(2, 2); ?>
52. Using Built-in Function
Inserting external files - continued:
The functions are identical in every way, except how they
handle errors.
The include() and include_once() functions generates a warning (but
the script will continue execution)
The require() and require_once() functions generates a fatal error
(and the script execution will stop after the error).
These functions are used to create functions, headers,
footers, or elements that can be reused on multiple pages.
This can save the developer a considerable amount of time for
updating/editing.
53. Date Function Formatting
DAYS
d - day of the month 2 digits (01-31)
j - day of the month (1-31)
D - 3 letter day (Mon - Sun)
l - full name of day (Monday - Sunday)
N - 1=Monday, 2=Tuesday, etc (1-7)
S - suffix for date (st, nd, rd)
w - 0=Sunday, 1=Monday (0-6)
z - day of the year (1=365)
WEEK
W - week of the year (1-52)
MONTH
F - Full name of month (January - December)
m - 2 digit month number (01-12)
n - month number (1-12)
M - 3 letter month (Jan - Dec)
t - Days in the month (28-31)
YEAR
L - leap year (0 no, 1 yes)
o - ISO-8601 year number (Ex. 1979, 2006)
Y - four digit year (Ex. 1979, 2006)
y - two digit year (Ex. 79, 06)
• Date Function
Formatting
• TIME
a - am or pm
A - AM or PM
B - Swatch Internet time
(000 - 999)
g - 12 hour (1-12)
G - 24 hour c (0-23)
h - 2 digit 12 hour (01-12)
H - 2 digit 24 hour (00-
23)
i - 2 digit minutes (00-59)
s 0 2 digit seconds (00-
59)
• OTHERe - timezone (Ex:
GMT, CST)
I - daylight savings
(1=yes, 0=no)
O - offset GMT (Ex:
0200)
Z - offset in seconds (-
43200 - 43200)
54. Using Built-in Function
PHP Date() function
formatting characters:
Example 1:
<?php
$theDate =
date("m/d/y");
echo "Today's date
is: $theDate";
?>
Example 2
<?php
$b = time ();
print date("m/d/y",$b) . "<br />";
print date("D, F jS",$b) . "<br />";
print date("l, F jS Y",$b) . "<br />";
print date("g:i A",$b) . "<br />";
print date("r",$b) . "<br />";
print date("g:i:s A D, F jS Y",$b) . "<br />";
?>
55. Defining and Referencing a
Function
Syntax
function functionname () { your code }
Example:
<html> <body>
<?php
Function Name()
{
echo "Ben John";
}
Name();
?>
</body> </html>
56. PHPFunctions - Adding
parameters
A parameter is just like a
variable.
The parameters are specified
inside the parentheses.
Syntax:
<?php
function
function_name(param_1,
... , param_n)
{
statement_1;
statement_2;
...
statement_m;
return
return_value;
}
?>
Functions can also be used to return
values.
Example:
<html>
<body>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
57. PHPArrays
An array can store one or more values in a
single variable name.
There are three different kind of arrays:
Numeric array - An array with a numeric ID key
Associative array - An array where each ID key is
associated with a value
Multidimensional array - An array containing one
or more arrays
58. Numeric Array
• A numeric array stores each element with
a numeric ID key.
• There are different ways to create a
numeric array:
Example 1
• In this example the ID key is
automatically assigned:
• $names =
array("Peter","Quagmire","Joe");
Example 2
• In this example we assign the ID key
manually:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
Example 3:
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " .
$names[2] . " are ".
$names[0] . "'s
neighbors"; ?>
59. Associative Arrays
• Each ID key is associated with a
value.
• When storing data about
specific named values, a
numerical array is not always
the best way to do it.
• There are two ways of creating
Associative Array:
Example 1
• $ages = array("Peter"=>32,
"Quagmire"=>30, "Joe"=>34);
Example 2
• $ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
Example 3:
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " .
$ages['Peter'] . " years
old.";
?>
60. Multidimensional Arrays
• In a multidimensional array,
each element in the main
array can also be an array.
And each element in the
sub-array can be an array,
and so on.
• Example 1
• with automatically assigned
ID keys:
$families = array
( "Griffin"=>array
( "Peter", "Lois", "Megan" ),
"Quagmire"=>array
( "Glenn" ),
"Brown"=>array
( "Cleveland", "Loretta", "Junior"
)
Example 2:
The array above would look like this if written to the
output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior )
)
• displaying a single value from the array
above:
echo "Is " . $families['Griffin'][2] . " a part of the
Griffin family?";
63. Forms: how they work
We need to know..
1. How forms work.
2. How to write forms in XHTML.
3. How to access the data in PHP.
64. How forms work
Web Server
User
User requests a particular URL
XHTML Page supplied with Form
User fills in form and submits.
Another URL is requested and the
Form data is sent to this page either in
URL or as a separate piece of data.
XHTML Response
65. XHTML Form
The form is enclosed in form tags..
<form action=“path/to/submit/page”
method=“get”>
<!–- form contents -->
</form>
66. Form tags
action=“…” is the page that the form should
submit its data to.
method=“…” is the method by which the form
data is submitted. The option are either get or
post. If the method is get the data is passed
in the url string, if the method is post it is
passed as a separate file.
67. Form fields: text input
Use a text input within form tags for a single
line freeform text input.
<label for=“fn">First Name</label>
<input type="text"
name="firstname"
id=“fn"
size="20"/>
68. Form tags
name=“…” is the name of the field. You will
use this name in PHP to access the data.
id=“…” is label reference string – this should
be the same as that referenced in the
<label> tag.
size=“…” is the length of the displayed text
box (number of characters).
69. Form fields: password input
Use a starred text input for passwords.
<label for=“pw">Password</label>
<input type=“password"
name=“passwd"
id=“pw"
size="20"/>
70. Form fields: text input
If you need more than 1 line to enter data, use
a textarea.
<label for="desc">Description</label>
<textarea name=“description”
id=“desc“
rows=“10” cols=“30”>
Default text goes here…
</textarea>
71. Form fields: text area
name=“…” is the name of the field. You will
use this name in PHP to access the data.
id=“…” is label reference string – this should
be the same as that referenced in the
<label> tag.
rows=“…” cols=“..” is the size of the
displayed text box.
72. Form fields: drop down
<label for="tn">Where do you live?</label>
<select name="town" id="tn">
<option value="swindon">Swindon</option>
<option value="london”
selected="selected">London</option>
<option value=“bristol">Bristol</option>
</select>
73. Form fields: drop down
name=“…” is the name of the field.
id=“…” is label reference string.
<option value=“…” is the actual data sent
back to PHP if the option is selected.
<option>…</option> is the value
displayed to the user.
selected=“selected” this option is
selected by default.
74. Form fields: radio buttons
<input type="radio"
name="age"
id="u30“
checked=“checked”
value="Under30" />
<label for="u30">Under 30</label>
<br />
<input type="radio"
name="age"
id="thirty40"
value="30to40" />
<label for="thirty40">30 to 40</label>
75. Form fields: radio buttons
name=“…” is the name of the field. All radio
boxes with the same name are grouped with
only one selectable at a time.
id=“…” is label reference string.
value=“…” is the actual data sent back to
PHP if the option is selected.
checked=“checked” this option is selected
by default.
76. Form fields: check boxes
What colours do you like?<br />
<input type="checkbox"
name="colour[]"
id="r"
checked="checked"
value="red" />
<label for="r">Red</label>
<br />
<input type="checkbox"
name="colour[]"
id="b"
value="blue" />
<label for="b">Blue</label>
77. Form fields: check boxes
name=“…” is the name of the field. Multiple
checkboxes can be selected, so if the button are
given the same name, they will overwrite
previous values. The exception is if the name is
given with square brackets – an array is
returned to PHP.
id=“…” is label reference string.
value=“…” is the actual data sent back to
PHP if the option is selected.
checked=“checked” this option is selected
by default.
79. Submit button..
A submit button for the form can be created
with the code:
<input type="submit"
name="submit"
value="Submit" />
80. Fieldset
In XHTML 1.0, all inputs must be grouped within the form into
fieldsets. These represent logical divisions through larger forms.
For short forms, all inputs are contained in a single fieldset.
<form>
<fieldset>
<input … />
<input … />
</fieldset>
<fieldset>
<input … />
<input … />
</fieldset>
</form>
81. In PHP…
The form variables are available to PHP in the
page to which they have been submitted.
The variables are available in two superglobal
arrays created by PHP called $_POST and
$_GET.
82. Access data
Access submitted data in the relevant array for
the submission type, using the input name as a
key.
<form action=“path/to/submit/page”
method=“get”>
<input type=“text” name=“email”>
</form>
$email = $_GET[‘email’];
83. A warning..
NEVER TRUST USER INPUT
Always check what has been input.
Validation can be undertaken using Regular
expressions or in-built PHP functions.
84. A useful tip..
I find that storing the validated data in a
different array to the original useful.
I often name this array ‘clean’ or something
similarly intuitive.
I then *only* work with the data in $clean, and
never refer to $_POST/$_GET again.
86. Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
$clean = array();
Initialise an array to store
filtered data.
87. Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
if (ctype_alnum($_POST['username']))
Inspect username to make
sure that it is alphanumeric.
88. Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
$clean['username'] = $_POST['username'];
If it is, store it in the array.
89. Is it submitted?
We also need to check before accessing data
to see if the data is submitted, use isset()
function.
if (isset($_POST[‘username’])) {
// perform validation
}
90. FORM Handling
GET
$_GET['name']
POST
$_POST['name']
or just use the more general method
$_REQUEST[‘name’]
91. FORM Example
<form action="test.php" method="post">
<table>
<tr>
<th>Name:</th>
<td><input type="text" name="name"></td>
</tr>
<tr>
<th>Age:</th>
<td><input type="text" name="age"></td>
</tr>
</table>
</form>
<p>Hello <?=$_POST['name']?>.
You are <?=$_POST['age']?> years old.</p>
92. Example
(a) A Web page
containing a form
(b) A PHP script for
handling the
output of the form
(c) Output from the
PHP script when
the inputs are
"Barbara" and 24
respectively
93.
94. The need for persistence
Consider these examples
− Counting the number of “hits” on a website
− i. e . how many times does a client load your web page
source
− The questionnaire on computing experience
Somehow your .php needs to remember previous
instances of it being requested by a client
95. Persistence
Persistence is the ability of data to outlive
the execution of the program that created
them.
An obvious way of achieving persistence is
to simply save the data in a file
96. Persistence and HTTP
Recall http is a stateless protocol. It remembers nothing about
previous transfers
Two ways to achieve persistence:
PHP cookies
PHP sessions
HTTP
serverClient
Cookie
Session
97. HTTP Cookies
In internet programming, a cookie is a packet of information sent from the
server to client, and then sent back to the server each time it is accessed by the
client.
Introduces state into HTTP (remember: HTTP is stateless)
Cookies are transferred between server and client according to http.
PHP supports http cookies
Cookies can also be thought of as tickets used to identify clients and their
orders
98. How Cookies are implemented
Cookies are sent from the server to the client via “Set-
Cookie” headers
Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
The NAME value is a URL-encoded name that identifies
the cookie.
The PATHand DOMAIN specify where the cookie applies
99. setcookie(name,value,expire,path,domain,secure
)
Parameter Description
name (Required). Specifies the name of the cookie
value (Required). Specifies the value of the cookie
expire (Optional). Specifies when the cookie expires.
e.g. time()+3600*24*30 will set the cookie to expire in 30 days.
If this parameter is not set, the cookie will expire at the end of the session (when
the browser closes).
path (Optional). Specifies the server path of the cookie.
If set to "/", the cookie will be available within the entire domain.
If set to "/phptest/", the cookie will only be available within the test directory and
all sub-directories of phptest.
The default value is the current directory that the cookie is being set in.
domain (Optional). Specifies the domain name of the cookie.
To make the cookie available on all subdomains of example.com then you'd set it
to ".example.com".
Setting it to www.example.com will make the cookie only available in the www
subdomain
secure (Optional). Specifies whether or not the cookie should only be transmitted over a
secure HTTPS connection.
TRUE indicates that the cookie will only be set if a secure connection exists.
Default is FALSE.
100. Cookies fromHTTPCookies fromHTTP
GET /*.html HTTP/1.1
Host: it026954.domain
GET /*.html HTTP/1.1
Host: it026945.domain
Cookie: name=value
Accept: */*
HTTP/1.1 200 OK
Content-type:
text/html
Set-Cookie:
name=value
(content of page)
Client (e.g. Firefox) it026945
101. Creating PHPcookiesCreating PHPcookies
Cookies can be set by directly manipulating the HTTP header using
the PHP header() function
<?php
header(“Set-Cookie: mycookie=myvalue; path=/; domain=.coggeshall.org”);
?>
102. Creating cookies with
setcookie()
Use the PHP setcookie() function:
Setcookie (name,value,expire, path, domain, secure)Setcookie (name,value,expire, path, domain, secure)
e.g.
<?php
setcookie("MyCookie", $value, time()+3600*24);
setcookie("AnotherCookie", $value, time()+3600);
?>
Name: name of the file
Value: data stored in the file
Expire: data string defining the life time
Path: subset of URLs in a domain where it is valid
Domain: domain for which the cookie is valid
Secure: set to '1' to transmit in HTTPS
103. Reading cookiesReading cookies
<?php
foreach ($_COOKIE as $key=>$val) {
print $key . " => " . $val . "<br/>";
}
?>
To access a cookie received from a client, use the PHP
$_COOKIE$_COOKIE superglobal array
Each key in the array represents a cookie - the key name is
the cookie name.
104. Creating and using cookiesCreating and using cookies
exampleexample
<?php
setcookie("MyCookie", $value, time()+7200);
setcookie("AnotherCookie", $value, time()+7);
?>
<?php
foreach ($_COOKIE as $key=>$val) {
print $key . " => " . $val . "<br/>";
}
?>
Cookies only become visible on the next page load
105. Using headers (wrong
approach!) <!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">
<head><title>PHP Script using Cookies</title>
<meta httpequiv="ContentType" content="text/html;
chatset=ISO88591" />
</head>
<body>
<?php
$strValue = "This is my first cookie";
setcookie ("mycookie", $strValue);
echo "Cookie set<br>";
?>
</body>
</html>
Gets an error!:
Warning: Cannot modify header information - headers already sent by (output started at
/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php:9) in
/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php on line 11
(adapted from Stobart & Parsons (2008))
106. Using headersUsing headers
setcookie() did not run before information
was sent to the browser...
Cookies have to be sent beforethe
heading elements
107. Using headers (correct
approach) <?php
$strValue = "This is my first cookie";
setcookie ("mycookie", $strValue);
echo "Cookie set<br>";
?>
<!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">
<head><title>PHP Script using Cookies</title>
<meta httpequiv="ContentType" content="text/html;
charset=ISO88591" />
</head>
<body>
<?php
echo “<p> A cookie has been set. </p>”;
?>This is the correct approach!
111. Where is the cookie stored
Depends on the browser...
e.g., firefox/mozilla under /home/a________
− Look for cookies.txt in .mozilla directory
− Usually under:
/home/a______/.mozilla/firefox/asdkfljy.default
− Cookie is stored only if there is an expiry date
− Otherwise it is deleted when leaving browser
− Persistent only if an e xpiry date is se t
112.
113. You can store user information (e.g. username,
items selected, etc.) in the serverside for later
use using PHP session.
SessionsSessions work by creating a unique id (UID) for
each visitor and storing variables based on this
UID.
The UID is either stored in a cookie or is
propagated in the URL.
PHPSessionsPHPSessions
114. When should you use sessions?When should you use sessions?
Need for data to stored on the server
Unique session information for each user
Transient data, only relevant for short time
Data does not contain secret information
Similar to Cookies, but it is stored on the
server
More secure, once established, no data is sent
back and forth between the machines
Works even if cookies are disabled
Example: we want to count the number of
“hits” on our web page.
116. PHPSessionsPHPSessions
Starting a PHP session:
<?php
session_start();
?>
• This tells PHP that a session is requested.
• A session ID is then allocated at the server end.
• session ID looks like:
sess_f1234781237468123768asjkhfa7891234g
118. Registering session variablesRegistering session variables
Instead of setting superglobals, one can register one’s
own session variables
<?php
$barney = “A big purple dinosaur.”;
$myvar_name = “barney”;
session_register($myvar_name);
?>
• $barney can now be accessed “globally” from session to
session
This only works if the register_globalsregister_globals directive is enabled
in php.ini - nowadays this is turned off by default
Use of session_register() is deprecated!
119. Make yourown session variablesMake yourown session variables
With session_start()session_start() a default session
variable is created - the name extracted
from the page name
To create your own session variable just
add a new key to the $_SESSION$_SESSION
superglobal
$_SESSION$_SESSION[‘dug’] = “a talking dog.”;
Use of $_SESSION is preferred, as of PHP 4.1.0.
120. Session Example 1
<?php
session_start();
if (!isset($_SESSION["intVar"]) ){
$_SESSION["intVar"] = 1;
} else {
$_SESSION["intVar"]++;
}
echo "<p>In this session you have accessed this
page " . $_SESSION["intVar"] . "times.</p>";
?>
122. Ending sessions
unset($_SESSION[‘name’])
–Remove a session variable
session_destroy()
– Destroys all data registered to a session
– does not unset session global variables and cookies
associated with the session
–Not normally done - leave to timeout
Can be used on characters too… (incrementing only, NOT decrementing) Follows Perl conventions… e.g. Code in initial.php : $i = "A"; $i++; echo $i; Output: B