SlideShare a Scribd company logo
1 of 126
CLIENT
WEB SERVER
HTTP Request
(url)
<HTML>
<?php PHP code ?>
</HTML>
Gets Page
<HTML>
<B>Hello</B>
</HTML>
Interprets the PHP cod
Server response
Browser creates
the web page
Hello
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.
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
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
• PHP adalah singkatan bagi PHP:
Hypertext Preprocessor
•
Dibangunkan oleh Rasmus Lerdorf pada
tahun 1994
•
Ia adalah pelayan-side berkuasa bahasa
skrip untuk mewujudkan laman web
yang dinamik dan interaktif.
•
Ia merupakan perisian sumber terbuka,
yang digunakan secara meluas dan
bebas untuk memuat turun dan
menggunakan (PHP adalah PERCUMA
untuk memuat turun dari sumber rasmi
PHP: www.php.net).
•
Ia merupakan alternatif yang berkesan
untuk pesaing seperti Microsoft ASP.
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,
Generic ODBC, etc.)
• PHP adalah amat sesuai untuk
pembangunan web dan boleh
diterapkan terus ke dalam kod
HTML.
•
Syntax PHP adalah hampir sama
dengan JavaScript, Perl dan C.
•
PHP sering digunakan bersama-
sama dengan Apache (web
server) dalam pelbagai sistem
operasi. Ia juga menyokong ISAPI
dan boleh digunakan dengan
Microsoft IIS pada Windows.
•
PHP menyokong banyak
pangkalan data (MySQL, Informix,
Oracle, Sybase, Pepejal,
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 
Introduction to PHP
What you need to develop PHPApplication:
• Install Apache (orIIS) on server, install PHP,
and MySQL
• OR
• Install Wampserver2 (a bundle of PHP, Apache,
and MySql server) on your own server/machine
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
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
• Apabila dokumen PHP diminta
pelayan, pelayan akan
menghantar dokumen pertama
dengan pemproses PHP.
•
Dua mod operasi:
Mod salinan di mana HTML
biasa disalin kepada output
•
Mod mentafsirdi mana kod
PHP ditafsirkan dan output
daripada kod yang dihantar ke
output
•
Pelanggan tidak pernah melihat
kod PHP, hanya output yang
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
• Penyata PHP ditamatkan dengan koma
bertitik;
•
Pendakap kerinting, {} digunakan untuk
membuat kenyataan kompaun
•
Pembolehubah tidak boleh ditakrifkan dalam
satu kenyataan kompaun melainkan jika ia
adalah badan fungsi
•
PHP mempunyai ciri-ciri bahasa skrip yang
biasa
- Menaip dinamik, pembolehubah un-ditaip
- array bersekutu
-pola yang sama
-perpustakaan yang luas
Primitif, Operasi, Expressions
-Empat jenis skalar: boolean, integer, double,
tali
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:
– #
– //
– /* . . . * /
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
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>
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!‘
?>
</body>
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)
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>";
?>
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
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;
?>
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.
Some Types of Operator
 Arithmetic
 Assignment
 Bitwise
 Comparison
 Ternary
• Incrementing
/decrementing
• Logical
• String
String Operators
 Use a dot to concatenate two strings:
e.g.
$firstname = ‘Rob’;
$surname = ‘Tuley’;
// displays ‘Rob Tuley’
echo $firstname.’ ‘.$surname;
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.
Assignment Operators
Example Result
$a = $b Sets $b to the same value as $a.
$a += $b Equivalent to $a = $a + $b.
$a .= $b Equivalent to $a = $a.$b.
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.
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.
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;
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.
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.
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)
Ternary Operator example
<?php
$a = 10;
$b = 13;
echo $a<$b ? ‘a smaller’:‘b smaller’;
// string ‘a smaller’ is echoed
// to the browser..
?>
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;
?>
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 . ".";
?>
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.
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
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>
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";
}
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
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++;
}
?>
</body>
<html>
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>
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>
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>
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
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.
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;
}
}
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();
?>
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);
?>
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
Using Built-in Fuctions
• Useful PHPString
Functions
Example - strlen() Function
<?php
$str = "Hello world!";
echo strlen($str);
?>
Example - strlen() Function
<?php
$str = “Hello world!”;
echo strpos(“$str”,"world");
?>
</body>
</html>
• Useful PHPString
Functions
<?php
echo strlen("Hello
world!");
echo "<br />";
echo strpos("Hello
world!","world");
?>
</body>
</html>
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>
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); ?>
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.
 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)
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 />";
?>
Defining and Referencing a
Function
Syntax
function functionname () { your code }
Example:
<html> <body>
<?php
Function Name()
{
echo "Ben John";
}
Name();
?>
</body> </html>
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>
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
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"; ?>
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.";
?>
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?";
Strings Function
 Strlen
 Strstr
 Strpos
 Substr
Forms
(Getting data from users)
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.
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
XHTML Form
 The form is enclosed in form tags..
<form action=“path/to/submit/page”
method=“get”>
<!–- form contents -->
</form>
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.
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"/>
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).
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"/>
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>
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.
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>
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.
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>
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.
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>
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.
Hidden Fields
<input type="hidden"
name="hidden_value"
value="My Hidden Value" />
 name=“…” is the name of the field.
 value=“…” is the actual data sent back to
PHP.
Submit button..
 A submit button for the form can be created
with the code:
<input type="submit"
name="submit"
value="Submit" />
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>
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.
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’];
A warning..
NEVER TRUST USER INPUT
 Always check what has been input.
 Validation can be undertaken using Regular
expressions or in-built PHP functions.
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.
Example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
$clean = array();
Initialise an array to store
filtered data.
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.
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.
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
}
FORM Handling
 GET
 $_GET['name']
 POST
 $_POST['name']
 or just use the more general method
 $_REQUEST[‘name’]
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>
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
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
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
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
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
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
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.
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
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”);
?>
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
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.
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
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 http­equiv="Content­Type" content="text/html; 
chatset=ISO­8859­1" />
 </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))
Using headersUsing headers
 setcookie() did not run before information
was sent to the browser...
 Cookies have to be sent beforethe
heading elements
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 http­equiv="Content­Type" content="text/html; 
charset=ISO­8859­1" />
 </head>  
 <body>
     <?php
         echo “<p> A cookie has been set. </p>”;
     ?>This is the correct approach!
Deleting a cookie

Set the cookie with its name only:
setcookie(“mycookie”);
Multiple data items

Use explode() e.g.
<?php
$strAddress = $_SERVER['REMOTE_ADDR'];
$strBrowser = $_SERVER['HTTP_USER_AGENT'];
$strOperatingSystem = $_ENV['OS'];
$strInfo = "$strAddress::$strBrowser::$strOperatingSystem";
setcookie ("somecookie4",$strInfo, time()+7200);
?>
<?php
$strReadCookie = $_COOKIE["somecookie4"];
$arrListOfStrings = explode ("::", $strReadCookie);
echo "<p>$strInfo</p>";
echo "<p>Your IP address is: $arrListOfStrings[0] </p>";
Where is the cookie stored?
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
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
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.
<?php session_start(); ?>
<html>
<body>
</body>
</html>
session_start() function must appear BEFORE the <html> tag.
Before you can store user information in your PHP
session, you must first start up the session.
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
Session variablesSession variables

$_SESSION

e.g., $_SESSION[“intVar”] = 10;

Testing if a session variable has been set:
session_start();
if(!$_SESSION['intVar']) {...} //intVar is set or not
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!
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.
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>";
 ?>
session_start();?>
age = $_SERVER['PHP_SELF'];
ameArray = explode('/', $thisPage);
ame = $pageNameArray[count($pageNameArray) ­ 1];
"The name of this page is: $pageName<br/>";
tems = explode(‘.', $pageName);
onName = $nameItems[0];
"The session name is $sessionName<br/>";
sset($_SESSION[$sessionName])) {
$_SESSION[$sessionName] = 0;
print "This is the first time you have visited this page<br/>";
 
$_SESSION[$sessionName]++;
"<h1>You have visited this page " . $_SESSION[$sessionName] . 
times</h1>";
Session Example 2Session Example 2
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
Destroying a session
completely
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) { // Returns the value of the configuration option
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
// Finally, destroy the session.
session_destroy();
?>
http://nz2.php.net/manual/en/function.session-destroy.
returns the name of the
current session
Session Example 3
 <?php
 session_start();
 if(!isset($_SESSION['strColourBg']))   $_SESSION['strColourBg'] = "red";
 else echo "Currently Bg set to " . $_SESSION['strColourBg'] . "<br>";
 if(!isset($_SESSION['strColourFg'])) $_SESSION['strColourFg'] = "yellow";
 else echo "Currently Fg set to " . $_SESSION['strColourFg'];
 if(isset($_POST["submit"]) ) {
   $strColourBg = $_POST["strNewBg"];
   $strColourFg = $_POST["strNewFg"];
   $_SESSION['strColourBg'] = $strColourBg;
   $_SESSION['strColourFg'] = $strColourFg;
   echo "<br>New Settings";
 }
 else {
   $strColourBg = $_SESSION['strColourBg'];
   $strColourFg = $_SESSION['strColourFg'];
   echo "<br>Keep old settings";
 }
 ?>
Session Example 3 (cont.) <head> <style type="text/css"> 
 body {background­color: <?php echo $strColourBg ?>}
 p {color: <?php echo $strColourFg?>}
 h2 {color: <?php echo $strColourFg?>}
 </style></head>
 <body>
 <h2>h2 colour</h2>
 <form action = '<?php echo $SERVER["PHP_SELF"] ?>' method='post'>
 <label for="strNewBg"> Background colour: </label>
 <select name='strNewBg' id='strNewBg'>
  <option>red</option> ...  <option>grey</option>
 </select>
 <label for="strNewFg"> Text colour: </label>
 <select name='strNewFg' id='strNewFg'>
  <option>yellow</option> ... <option>grey</option>
 </select>
 <input type='submit' name='submit'/>
 </form></body>
 (adapted from Stobart & Parsons, 2008)
Examples
 php_imagefields.php
 php_retention.php
 upload.html
 upload.php
 php_imagefields.php
 php_imagecreation.php
 php_truetypefonts.php
 php_file_get_contents.php
 php_cookie_multipledata.p
hp
 cookie1.php
 cookie_with_headers.php
session1.php
session2.php
php_session_colours2.php
php_session_destroy.php
Summary
PHP sessions and cookies are mechanisms
for introducing state into HTTP
transactions.

More Related Content

What's hot

Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting languageElmer Concepcion Jr.
 
Constructor and encapsulation in php
Constructor and encapsulation in phpConstructor and encapsulation in php
Constructor and encapsulation in phpSHIVANI SONI
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersMohammed Mushtaq Ahmed
 
PHP, PHP Developer, Hire PHP Developer, PHP Web Development, Hire PHP Program...
PHP, PHP Developer, Hire PHP Developer, PHP Web Development, Hire PHP Program...PHP, PHP Developer, Hire PHP Developer, PHP Web Development, Hire PHP Program...
PHP, PHP Developer, Hire PHP Developer, PHP Web Development, Hire PHP Program...bchrisopher
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive OverviewMohamed Loey
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntaxDhani Ahmad
 

What's hot (20)

Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Ph pbasics
Ph pbasicsPh pbasics
Ph pbasics
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Constructor and encapsulation in php
Constructor and encapsulation in phpConstructor and encapsulation in php
Constructor and encapsulation in php
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
Php basics
Php basicsPhp basics
Php basics
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
PHP, PHP Developer, Hire PHP Developer, PHP Web Development, Hire PHP Program...
PHP, PHP Developer, Hire PHP Developer, PHP Web Development, Hire PHP Program...PHP, PHP Developer, Hire PHP Developer, PHP Web Development, Hire PHP Program...
PHP, PHP Developer, Hire PHP Developer, PHP Web Development, Hire PHP Program...
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive Overview
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Lecture8
Lecture8Lecture8
Lecture8
 
Php introduction
Php introductionPhp introduction
Php introduction
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
Php unit i
Php unit iPhp unit i
Php unit i
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
01 Php Introduction
01 Php Introduction01 Php Introduction
01 Php Introduction
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntax
 

Similar to Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)

Similar to Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23) (20)

Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
PHP
PHPPHP
PHP
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdf
 
php fundamental
php fundamentalphp fundamental
php fundamental
 
Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
 
php
phpphp
php
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
PHP ITCS 323
PHP ITCS 323PHP ITCS 323
PHP ITCS 323
 
Php Basics
Php BasicsPhp Basics
Php Basics
 
INTRODUCTION to php.pptx
INTRODUCTION to php.pptxINTRODUCTION to php.pptx
INTRODUCTION to php.pptx
 
Ppt php
Ppt phpPpt php
Ppt php
 
Php converted pdf
Php converted pdfPhp converted pdf
Php converted pdf
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
05php
05php05php
05php
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 

More from Muhamad Al Imran

More from Muhamad Al Imran (7)

Perbezaan ASWJ dengan Syiah
Perbezaan ASWJ dengan SyiahPerbezaan ASWJ dengan Syiah
Perbezaan ASWJ dengan Syiah
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
Discussion 2 q
Discussion 2 qDiscussion 2 q
Discussion 2 q
 
Lab5 tips
Lab5 tipsLab5 tips
Lab5 tips
 
Php i basic chapter 4
Php i basic chapter 4Php i basic chapter 4
Php i basic chapter 4
 
Discussion2 tips
Discussion2 tipsDiscussion2 tips
Discussion2 tips
 
Discussion 1 q
Discussion 1 qDiscussion 1 q
Discussion 1 q
 

Recently uploaded

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)

  • 1. CLIENT WEB SERVER HTTP Request (url) <HTML> <?php PHP code ?> </HTML> Gets Page <HTML> <B>Hello</B> </HTML> Interprets the PHP cod Server response Browser creates the web page Hello
  • 2. 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.
  • 3. 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
  • 4. 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 • PHP adalah singkatan bagi PHP: Hypertext Preprocessor • Dibangunkan oleh Rasmus Lerdorf pada tahun 1994 • Ia adalah pelayan-side berkuasa bahasa skrip untuk mewujudkan laman web yang dinamik dan interaktif. • Ia merupakan perisian sumber terbuka, yang digunakan secara meluas dan bebas untuk memuat turun dan menggunakan (PHP adalah PERCUMA untuk memuat turun dari sumber rasmi PHP: www.php.net). • Ia merupakan alternatif yang berkesan untuk pesaing seperti Microsoft ASP.
  • 5. 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, Generic ODBC, etc.) • PHP adalah amat sesuai untuk pembangunan web dan boleh diterapkan terus ke dalam kod HTML. • Syntax PHP adalah hampir sama dengan JavaScript, Perl dan C. • PHP sering digunakan bersama- sama dengan Apache (web server) dalam pelbagai sistem operasi. Ia juga menyokong ISAPI dan boleh digunakan dengan Microsoft IIS pada Windows. • PHP menyokong banyak pangkalan data (MySQL, Informix, Oracle, Sybase, Pepejal,
  • 6. 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 
  • 7. Introduction to PHP What you need to develop PHPApplication: • Install Apache (orIIS) on server, install PHP, and MySQL • OR • Install Wampserver2 (a bundle of PHP, Apache, and MySql server) on your own server/machine
  • 8. 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
  • 9. 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 • Apabila dokumen PHP diminta pelayan, pelayan akan menghantar dokumen pertama dengan pemproses PHP. • Dua mod operasi: Mod salinan di mana HTML biasa disalin kepada output • Mod mentafsirdi mana kod PHP ditafsirkan dan output daripada kod yang dihantar ke output • Pelanggan tidak pernah melihat kod PHP, hanya output yang
  • 10. 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 • Penyata PHP ditamatkan dengan koma bertitik; • Pendakap kerinting, {} digunakan untuk membuat kenyataan kompaun • Pembolehubah tidak boleh ditakrifkan dalam satu kenyataan kompaun melainkan jika ia adalah badan fungsi • PHP mempunyai ciri-ciri bahasa skrip yang biasa - Menaip dinamik, pembolehubah un-ditaip - array bersekutu -pola yang sama -perpustakaan yang luas Primitif, Operasi, Expressions -Empat jenis skalar: boolean, integer, double, tali
  • 11. 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: – # – // – /* . . . * /
  • 12. 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
  • 13. 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>
  • 14. 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!‘ ?> </body>
  • 15. 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)
  • 16. 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>"; ?>
  • 17. 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
  • 18. 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; ?>
  • 19. 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.
  • 20. Some Types of Operator  Arithmetic  Assignment  Bitwise  Comparison  Ternary • Incrementing /decrementing • Logical • String
  • 21. String Operators  Use a dot to concatenate two strings: e.g. $firstname = ‘Rob’; $surname = ‘Tuley’; // displays ‘Rob Tuley’ echo $firstname.’ ‘.$surname;
  • 22. 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.
  • 23. Assignment Operators Example Result $a = $b Sets $b to the same value as $a. $a += $b Equivalent to $a = $a + $b. $a .= $b Equivalent to $a = $a.$b.
  • 24. 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.
  • 25. 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.
  • 26. 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;
  • 27. 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.
  • 28. 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.
  • 29. 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)
  • 30. Ternary Operator example <?php $a = 10; $b = 13; echo $a<$b ? ‘a smaller’:‘b smaller’; // string ‘a smaller’ is echoed // to the browser.. ?>
  • 31. 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; ?>
  • 32. 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 . "."; ?>
  • 33. 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.
  • 34. 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
  • 35. 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>
  • 36. 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"; }
  • 37. 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
  • 38. 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++; } ?> </body> <html>
  • 39. 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>
  • 40. 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>
  • 41. 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>
  • 42. 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
  • 43. 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.
  • 44. 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; } }
  • 45. 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(); ?>
  • 46. 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); ?>
  • 47. 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
  • 48. Using Built-in Fuctions • Useful PHPString Functions Example - strlen() Function <?php $str = "Hello world!"; echo strlen($str); ?> Example - strlen() Function <?php $str = “Hello world!”; echo strpos(“$str”,"world"); ?> </body> </html> • Useful PHPString Functions <?php echo strlen("Hello world!"); echo "<br />"; echo strpos("Hello world!","world"); ?> </body> </html>
  • 49. 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>
  • 50. 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); ?>
  • 51. 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.
  • 52.  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)
  • 53. 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 />"; ?>
  • 54. Defining and Referencing a Function Syntax function functionname () { your code } Example: <html> <body> <?php Function Name() { echo "Ben John"; } Name(); ?> </body> </html>
  • 55. 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>
  • 56. 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
  • 57. 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"; ?>
  • 58. 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."; ?>
  • 59. 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?";
  • 60. Strings Function  Strlen  Strstr  Strpos  Substr
  • 62. 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.
  • 63. 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
  • 64. XHTML Form  The form is enclosed in form tags.. <form action=“path/to/submit/page” method=“get”> <!–- form contents --> </form>
  • 65. 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.
  • 66. 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"/>
  • 67. 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).
  • 68. 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"/>
  • 69. 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>
  • 70. 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.
  • 71. 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>
  • 72. 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.
  • 73. 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>
  • 74. 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.
  • 75. 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>
  • 76. 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.
  • 77. Hidden Fields <input type="hidden" name="hidden_value" value="My Hidden Value" />  name=“…” is the name of the field.  value=“…” is the actual data sent back to PHP.
  • 78. Submit button..  A submit button for the form can be created with the code: <input type="submit" name="submit" value="Submit" />
  • 79. 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>
  • 80. 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.
  • 81. 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’];
  • 82. A warning.. NEVER TRUST USER INPUT  Always check what has been input.  Validation can be undertaken using Regular expressions or in-built PHP functions.
  • 83. 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.
  • 84. Example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; }
  • 85. Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean = array(); Initialise an array to store filtered data.
  • 86. 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.
  • 87. 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.
  • 88. 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 }
  • 89. FORM Handling  GET  $_GET['name']  POST  $_POST['name']  or just use the more general method  $_REQUEST[‘name’]
  • 90. 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>
  • 91. 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
  • 92.
  • 93. 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
  • 94. 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
  • 95. 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
  • 96. 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
  • 97. 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
  • 98. 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.
  • 99. 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
  • 100. 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”); ?>
  • 101. 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
  • 102. 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.
  • 103. 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
  • 104. 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 http­equiv="Content­Type" content="text/html;  chatset=ISO­8859­1" />  </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))
  • 105. Using headersUsing headers  setcookie() did not run before information was sent to the browser...  Cookies have to be sent beforethe heading elements
  • 106. 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 http­equiv="Content­Type" content="text/html;  charset=ISO­8859­1" />  </head>    <body>      <?php          echo “<p> A cookie has been set. </p>”;      ?>This is the correct approach!
  • 107. Deleting a cookie  Set the cookie with its name only: setcookie(“mycookie”);
  • 108. Multiple data items  Use explode() e.g. <?php $strAddress = $_SERVER['REMOTE_ADDR']; $strBrowser = $_SERVER['HTTP_USER_AGENT']; $strOperatingSystem = $_ENV['OS']; $strInfo = "$strAddress::$strBrowser::$strOperatingSystem"; setcookie ("somecookie4",$strInfo, time()+7200); ?> <?php $strReadCookie = $_COOKIE["somecookie4"]; $arrListOfStrings = explode ("::", $strReadCookie); echo "<p>$strInfo</p>"; echo "<p>Your IP address is: $arrListOfStrings[0] </p>";
  • 109. Where is the cookie stored?
  • 110. 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
  • 111.
  • 112. 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
  • 113. 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.
  • 114. <?php session_start(); ?> <html> <body> </body> </html> session_start() function must appear BEFORE the <html> tag. Before you can store user information in your PHP session, you must first start up the session.
  • 115. 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
  • 116. Session variablesSession variables  $_SESSION  e.g., $_SESSION[“intVar”] = 10;  Testing if a session variable has been set: session_start(); if(!$_SESSION['intVar']) {...} //intVar is set or not
  • 117. 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!
  • 118. 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.
  • 119. 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>";  ?>
  • 121. 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
  • 122. Destroying a session completely <?php // Initialize the session. // If you are using session_name("something"), don't forget it now! session_start(); // Unset all of the session variables. $_SESSION = array(); // If it's desired to kill the session, also delete the session cookie. // Note: This will destroy the session, and not just the session data! if (ini_get("session.use_cookies")) { // Returns the value of the configuration option     $params = session_get_cookie_params();     setcookie(session_name(), '', time() - 42000,         $params["path"], $params["domain"],         $params["secure"], $params["httponly"]     ); } // Finally, destroy the session. session_destroy(); ?> http://nz2.php.net/manual/en/function.session-destroy. returns the name of the current session
  • 123. Session Example 3  <?php  session_start();  if(!isset($_SESSION['strColourBg']))   $_SESSION['strColourBg'] = "red";  else echo "Currently Bg set to " . $_SESSION['strColourBg'] . "<br>";  if(!isset($_SESSION['strColourFg'])) $_SESSION['strColourFg'] = "yellow";  else echo "Currently Fg set to " . $_SESSION['strColourFg'];  if(isset($_POST["submit"]) ) {    $strColourBg = $_POST["strNewBg"];    $strColourFg = $_POST["strNewFg"];    $_SESSION['strColourBg'] = $strColourBg;    $_SESSION['strColourFg'] = $strColourFg;    echo "<br>New Settings";  }  else {    $strColourBg = $_SESSION['strColourBg'];    $strColourFg = $_SESSION['strColourFg'];    echo "<br>Keep old settings";  }  ?>
  • 124. Session Example 3 (cont.) <head> <style type="text/css">   body {background­color: <?php echo $strColourBg ?>}  p {color: <?php echo $strColourFg?>}  h2 {color: <?php echo $strColourFg?>}  </style></head>  <body>  <h2>h2 colour</h2>  <form action = '<?php echo $SERVER["PHP_SELF"] ?>' method='post'>  <label for="strNewBg"> Background colour: </label>  <select name='strNewBg' id='strNewBg'>   <option>red</option> ...  <option>grey</option>  </select>  <label for="strNewFg"> Text colour: </label>  <select name='strNewFg' id='strNewFg'>   <option>yellow</option> ... <option>grey</option>  </select>  <input type='submit' name='submit'/>  </form></body>  (adapted from Stobart & Parsons, 2008)
  • 125. Examples  php_imagefields.php  php_retention.php  upload.html  upload.php  php_imagefields.php  php_imagecreation.php  php_truetypefonts.php  php_file_get_contents.php  php_cookie_multipledata.p hp  cookie1.php  cookie_with_headers.php session1.php session2.php php_session_colours2.php php_session_destroy.php
  • 126. Summary PHP sessions and cookies are mechanisms for introducing state into HTTP transactions.

Editor's Notes

  1. Can be used on characters too… (incrementing only, NOT decrementing) Follows Perl conventions… e.g. Code in initial.php : $i = &quot;A&quot;; $i++; echo $i; Output: B