Introduction to PHP
Introduction to PHP
IT135L : E-Commerce Lab
A
Anna Ch
Christina
i ti Rotor,
R t MIT
Before PHP
• In the beginning…there was a clamor:
– To manipulate HTML form data in real time
– To provide dynamic content
• In the early days…there was C
• Clamor for simpler languages for web
programming…then there was Perl
• People were happy with Perl
Clamor for PHP
• Clamor for having web programming logic
within the HTML page
• Ability to template parts of the HTML page
j oriented
• Object
• Expandability to support additional future
features
PHP
• Recursive acronym for: PHP: Hypertext Processor
• Open Source (basically its free)
• Server-side (typically runs as part of a web server)
• Cross-platform (ported to a large number of OSes)
• HTML embedded scripting language
• PHP code typically ends with a .php extension
PHP
• Output not limited to HTML, it can also generate images, PDF files,
XML/text and even flash movies
• Can be integrated with a large number of database platforms:
– Oracle
– dBase
– InterBase
– PostgreSQL
– Sybase
– IBM DB2
– MySQL
– Informix
I f i
– ODBC
First PHP Program
<html>
<head>
<title>My First PHP Program</title>
</head>
<body>
<?php
echo
h “Hello
“H ll World!<br>”;
W ld! b ”
?>
</body>
</html>
Embedding PHP
<?php if (strstr($HTTP_USER_AGENT, “MSIE”)) {
?>
<b>You are using Internet Explorer</b>
p p } else { ?>
<?php
<b>You are not using Internet Explorer</b>
<?php
?php } ?>
?
Commenting Out Code
<!-- Hi! I am an HTML comment -->
<?php
echo “This is a test”; //one line C-style comment
/* This is a multi-line comment
yet another line of comment */
echo “This is another test”;
echo
h “One
“O final
fi l test”;
” #shell-style
# h ll l comment
?>
Data Types
• Dynamic typing
• Automatic type conversion
• Typical data types include
– Numbers (integer or real)
• Decimal 1234,
1234 Octal 0777,
0777 He
Hexadecimal
adecimal 0xff
0 ff
– Strings
• Double-quoted “anna”, single-quoted ‘rotor’
– Boolean
• true, false
– Objects
PHP and variables
• PHP variables are case-sensitive; $count is different from
$Count or $COUNT
<html><body>
<h2>Q: This creature has tusks made of ivory.
What
h isi its
i name?</h2>
/h
<?php
//define variable
$answer = ‘Elephant’;
//print output
echo “<h2><i>$answer</i></h2>”;
$ ;
?>
</body></html>
Values and Assignment
<?php
$age
g = $dob + 15;;
?>
p p
<?php
$today = “April 28, 2006”;
echo “Today
Today is $today
$today”;;
?>
Handling Forms
• Forms have always been the quickest and easiest
way to add interactivity to your web site
<html><body>
<form action
action=“message
message.php
php” method
method=“post”>
post >
Enter your message: <input type =“text” name=“msg” size=“30”>
<input type=“submit” value=“Send”>
</form>
</body></html>
message.html
g
Handling Forms
• The most critical line in the entire message.html is the <form> tag:
<form
form method
method=“post”
post action
action=“message.php”>
message.php
…
</form>
• The method attribute of the <form> tag specifies the manner in which
form data will be submitted (POST)
• The action attribute specifies the name of the server-side
server side script
(message.php) that will process the information entered into the form
Handling Forms
<?php
//retrieve data in a variable
$input = $_POST[‘msg’];
//print it
echo “You
You said: <i>$input</i>”;
i $input /i ;
?>
message.php
Handling Forms
• Whenever a form is POST-ed to a PHP script, all
variable-value pairs within that form
automatically become available for use within the
script through a special PHP container variable,
$ POST
$_POST
• If the form uses GET instead of POST, simply
retrieve
ti values
l from
f $_GET
$ GET instead
i t d off $_POST
$ POST
• The $_GET and $_POST variables are a special
t
type off animal
i l called
ll d an array
Detecting Variable Data Type
• To find out what type a particular variable is, PHP offers
the gettype() function
<?php
// define variables
$auth = true;
$age = 18;
$name = ‘Anna’;
$tempp = 36.6;
Detecting Variable Data Type
• //returns “string”
echo gettype($name);
• //returns “boolean”
echo gettype($auth);
• //returns “integer”
echo gettype($age);
• //returns
// t “double”
“d bl ”
echo gettype($temp);
Other ‘detectors’
• is_bool()
• is_string()
• is_numeric()
• is_float()
• is int()
is_int()
• is_null()
• is_array()
_ y()
• is_object()
String values
• String values enclosed in double quotes
automatically
au o a ca y parsed
pa sed for
o variable
va ab e names
a es
• If variable names are found, they are
automatically replaced with the appropriate
variable value
String values
<?php
$identity = ‘James Bond’;
$ = ‘BMW’;
$car ‘BMW’
//this would contain the string “James Bond drives a
//BMW”
$sentence = “$identity drives a $car”;
//this would contain the string “$identity drives a $car”
$sentence = ‘$identity drives a $car’;
?>
String values
• If you string contains quotes, carriage returns, or
backslashes, it’s necessary to escape these special
characters with a backslash
<?php
// ill cause an error due
//will d tot mismatched
i t h d quotes
t
$statement = ‘It’s hot outside’;
//will be fine
$statement = ‘It\’s hot outside’;
?>
String Operators
• To add strings together, use the string concatenation
operator, represented by a period (.).
//sample concatenation 1
$username = ‘john’; $domain = ‘example.com’;
//combine them using
sing the concatenation operator
$email = $username . ‘@’ . $domain; echo $email;
//sample concatenation 2
$ = ‘the’;
$str ‘h ’
//add and assign
$str .= ‘n’; echo $str;
Comparison Operators
• To test whether two variables are different, use any one
of PHP’s many comparison operators
$mean = 29; $median = 40; $mode = 29;
//less than operator
$res lt = ($mean < $median); //true
$result //tr e
//greater than operator
$result = ($mean > $median); //false
//l than
//less h or equall to operator
$result = ($median <= $mode); //false
Comparison Operators
//greater than or equal to operator
$result = ($median >= $mode); //true
//equality operator
$result = ($mean == $mode); //true
//not equal to operator
$result = ($mean != $mode); //false
//inequality operator
$result = ($mean <> $mode); //false
The === Operator
• Another important comparison operator in PHP is the
=== operator
<?php
$ t = ’14’;
$str ’14’
$int = 14;
$result = ($str == $int); //true
$result = ($str === $int); //false
?>
Other Relevant Operators
• Logical operators = AND, OR, NOT
– &&,
&& ||,
|| !
• Auto-increment and Auto-decrement
operators
– ++,, --
• Arithmetic operators
– +, -, *, /, %
Conditional Statements
• if-elseif-else
if ($country
($ t == ‘UK’)
$capital = ‘London’;
elseif ($country == ‘US’)
US )
$capital = ‘Washington’;
elseif ($country == ‘FR’)
$capital = ‘Paris’;
else
$ it l = ‘Unknown’;
$capital ‘U k ’
Conditional Statements
• Switch
switch ($country)
{ case ‘UK’:
$capital = ‘London’; break;
case ‘US’:
‘US’
$capital = ‘Washington’; break;
case ‘FR’:
$capital = ‘Paris’; break;
default:
$capital = ‘Unknown’; break;
}
Loops
• A loop is a control structure that enables you to
repeat the same set of statements or commands
over andd over again
i
– while() loop
<?php
while (condition is true)
{
do this;
}
?>
Loops
• Cont…
– do-while()
() loop
p
<?php
do
{
do this;;
} while (condition is true)
?>
Loops
• Cont…
– for()
() loopp
for (initialize counter; conditional test; update
counter)
{
do this;
}
?>
while() Loop
• So long as the conditional expression specified evaluates
to true, the loop will continue to execute
$num = 11; $u_limit = 10; $l_limit = 1;
//l
//loop andd multiply
lti l to
t create
t table
t bl
while ($l_limit <= $u_limit)
{
echo “$num x $l_limit = “ . ($num * $l_limit);
$l limit++;
$l_limit++;
}
do‐while() Loop
• Sometimes, you might need to execute a set of statements
at least once, regardless of how the conditional
expression evaluates
$num = 11; $u_limit = 10; $l_limit = 1;
//loop and multiply to create table
do
{
echo “$num x $l_limit = “ . ($num * $l_limit);
$l_limit++;
} while ($l_limit <= $u_limit);
for() loop
• Both the while() and do-while() loops continue to iterate
for so long as the specified conditional expression
remains true. But there often arises a need to execute a
certain set of statements a fixed number of times
for ($x = 2; $x <= 100; $x++)
{
echo “$x”;
}
Break
• The break keyword is used to exit a loop when it
encounters and unexpected situation
for ($x = -10; $x <= 10; $x++)
{
if ($x == 0)
break;
echo ‘100 / ‘ . $x . ‘ = ‘ . (100/$x);
}
Continue
• The continue keyword is used to skip a particular iteration
of the loop and move to the next iteration immediately
for ($x
$ = 10; $x$ <= 100; $$x++)
{
if (($x
(($ % 12) == 0)
{ echo “$x “; }
else
continue;
}
Arrays
• To define an array variable, name it using standard PHP
variable naming rules and populate it with elements using
th array()
the () function
f ti
//define an array
$flavors = array(‘strawberry’, ‘grape’, ‘vanilla’, ‘caramel’,
‘chocolate’);
);
Arrays
• An alternative way to define an array is by specifying
values for each element using index notation
//define an array
$flavors[0]
[ ] = ‘strawberry’;
y;
$flavors[1] = ‘grape’;
$flavors[2] = ‘vanilla’;
$fl
$flavors[3]
[3] = ‘caramel’;
‘ l’
$flavors[4] = ‘chocolate’;
Associative Arrays
• PHP also enables you to replace indices with
user-defined “keys” to create a slightly different
type of array
• Each key is unique, and corresponds to a single
value within the array
• Keys may be made up of any string of characters
Associative Arrays
//define associative array
$fruits = array(‘red’ => ‘apple’, ‘yellow’ => ‘banana, ‘purple’ =>
‘
‘grape’,
’ ‘green’
‘ ’ =>
> ‘mango’);
‘ ’)
//alternate way
$fruits[‘red’] = ‘apple’;
$fruits[‘yellow’] = ‘banana’;
$fruits[‘purple’] = ‘grape’;
$fruits[‘green’] = ‘mango’;
Modifying Array Elements
• To add an element to an array, assign a value using the
next available index number or key
//add an element to a numeric array
$flavors[5] = ‘mango’;
//if you don’t know the next available index
//this will also work
$flavors[ ] = ‘mango’;
Processing arrays with loops
<html><body>
Today’s shopping list: <u1>
<?php
$shoppingList = array (‘potatoes’, ‘tomatoes’, ‘mangoes’);
for ($x = 0; $x < sizeof($shoppingList); $x++)
echo “<li>$shoppingList[$x]”;
pp g [ ]
?>
</u1> </body></html>
foreach() loop
• This loop runs once for each element of the array, moving
forward through the array on each iteration
• On each run, the statements within the curly braces are
executed, and the currently selected array element is
made available through a temporary loop variable
• Unlike a for() loop, a foreach() loop doesn’t need a
counter or a call to the sizeof()
• foreach() keeps track of its position in the array
automatically
foreach() loop
<html><body>
Today’s shopping list: <u1>
<?php
$shoppingList = (‘potatoes’, ‘tomatoes’, ‘mangoes’);
foreach($shoppingList as $item)
echo “<li>$item”;
?>
</u1></body></html>
Array Functions
• is_array() – returns true if the variable is an array
• list() – assigns array elements to variables
• extract() – iterates through a hash, converting the key-
value pairs into corresponding variable-value pairs
• explode()
l d () – splits
lit a string
t i into
i t smaller
ll components t on the
th
basis of a user-specified pattern, and returns these
elements as an arrayy
• implode() – creates a single string from all the elements
of an array, joining them together with a user defined
separator
t
is_array()
$desserts = arrayy ((‘chocolate mousse’,, ‘tiramisu’);
);
//returns 1 (true)
echo is_array($desserts);
list()
$flavors = array(‘strawberry’, ‘grape’, ‘vanilla’);
//extract values into variables
list ($flavor1, $flavor2, $flavor3) = $flavors;
//returns “strawberry”
echo
h $flavor1;
$fl 1
extract()
$fruits = array(‘red’ => ‘apple’, ‘yellow’ =>
‘banana’, ‘purple’ => ‘grape’, ‘green’ =>
‘mango’);
//extract values into variables
($ );
extract($fruits);
//returns “banana”
banana
echo $yellow;
explode()
$string = ‘English Latin Filipino French’;
//split on whitespace
$languages = explode(‘ ‘, $string);
//$languages now contains (‘English’, ‘Latin’, ‘Filipino’,
‘French’
French
implode()
$string = ‘English Latin Filipino French’;
//split
p on whitespace
p
$languages = explode(‘ ‘, $string);
g
//create new string
//returns “English and Latin and Filipino and French”
$newstring = implode(
implode(“ and “,, $languages);
echo $newstring;
Creating User‐Defined Functions
• A function is simply a set of program statements that
perform a specific task
• Can be called or executed from anywhere in your
program
• Functions are a good thing for three important reasons
– Reduces unnecessary code repetition and redundancies
– Defined once,
once therefore they are easy to maintain
– Provide abstraction, thus encouraging better software
design
Defining and Invoking Functions
//define a function
function getTriangleArea($base, $height)
{
$area = $base * $height * 0.5;
return $area;
}
//invoke a function
echo ‘The area of a triangle with base 10 and height 50 is ‘ .
getTriangleArea(10, 50);
File Handling
• To check whether a particular file exists, use the
file_exists() function. This function returns true
if a files does exist, and false otherwise
• To copy file contents from a file to a variable, use
the file() function
• file_get_contents() and file_put_contents may
also be used to read and write files
File Handling
//assign filename to variable
$file = “catalog.txt”;
if (file_exists($file))
(fil i t ($fil ))
{
$data = file($file);
foreach($data as $line)
{ echo “$line <br>”; }
}
else
{ die(“Could
di (“C ld nott find
fi d catalog
t l file”);
fil ”) }
Sessions
• HTML is a stateless protocol
– Each request for a web page is unique and independent
– No
N relationship
l i hi whatsoever
h to the
h transactions
i that
h preceded
d d it
i
– This is a big problem for transaction-based sites
• PHP sessions are methods to make HTML pages
‘stateful’
– Stores information about each client and track its activites
– Session data is preserved for the duration of the visit, and is
usually destroyed on its conclusion
Creating a session and registering
d
session variables
• The session_start( ) function is used to create a client
session and generate a session ID
• Once a session has been created, it becomes possible to
register any number of session variables
– Regular variables which can store textual or numeric information
– These variables can be manipulated by standard PHP functions,
but are unique to each client
– Session variables may be registered as key-value pairs in the
special $_SESSION array
Creating a session and registering
d
session variables
//first page
//create a session
session_start();
//register some session variables
$_SESSION[‘username’] = ‘anna’;
$ SESSION[‘ l ’] = ‘‘admin’;
$_SESSION[‘role’] d i ’
Creating a session and registering
d
session variables
//second page
//re-create the previous session
session_start();
//print the value of the session variable
echo $_SESSION[‘username’];
Destroying a session
• To destroy a session, reset the $_SESSION array and then
use the session_destroy() function to erase session data
//re-create session
session_start();
//reset session array
$ SESSION = array();
$_SESSION
//destroy session
session_destroy();