IT135L - Intro To PHP
IT135L - Intro 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
<?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
//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’;
//returns 1 (true)
echo is_array($desserts);
list()
$flavors = array(‘strawberry’, ‘grape’, ‘vanilla’);
//returns “strawberry”
echo
h $flavor1;
$fl 1
extract()
$fruits = array(‘red’ => ‘apple’, ‘yellow’ =>
‘banana’, ‘purple’ => ‘grape’, ‘green’ =>
‘mango’);
//returns “banana”
banana
echo $yellow;
explode()
$string = ‘English Latin Filipino French’;
//split on whitespace
$languages = explode(‘ ‘, $string);
//destroy session
session_destroy();