Server-side Programming in PHP
History of PHP
• PHP originally stood for “Personal Home Page”
• It started out, in 1994, as a simple preprocessor of HTML
files
– built by Rasmus Lerdorf (born in Greenland, grew up in Denmark
and Canada, graduated from U of Waterloo in 1993, now
prominent member of Open Source movement)
– original purpose was to log people who viewed his on-line resume
• Since then, has been developed by a growing community
of open source developers
• Name now supposed to stand for “Hypertext Pre-
Processor”
PHP history (contd.)
• Initially, PHP comprised a simple parser plus a
library of C functions
• The parser would scan a HTML file looking for
instances of a new non-standard tag and replace
the contents of these tag instances with the result
of executing some functions in the C library
• As a result, much PHP syntax looks like C
• Other parts of it, however, have a Perl flavour –
but, of course, Perl also borrows C syntax
Enabling PHP in HTTP servers
• PHP is available on many servers today, in
Windows and all types of Unix
environments
• It is supported by Apache, AOLServer,
Roxen and others
• Servers can be configured to enable PHP in
different ways
• We will assume that the httpd recognizes a
file who name has the suffix .php as a PHP
file
A first PHP file
PHP Test
Hello World"; ?>
How PHP files are processed
• The httpd demon simply copies regular HTML content in
the .php file to the message body that will be sent to a
client which requests the .php file
• The new non-standard tag is of the form
• The text inside the tag is PHP code
Hello World"; ?>
• The httpd demon executes this PHP code and copies the
output text, generated by this PHP code, to the message
body that will be sent to the client
• Thus, from the above, the client would see only
Hello World
Suppose we request this file
cosmos.ucc.ie> telnet csweb.ucc.ie 80
Trying 143.239.75.219...
Connected to csweb.ucc.ie.
Escape character is '^]'.
GET /j.bowen/cs3314/demos/file1.php
Here is the response
PHP Test
Hello World
Connection closed by foreign host.
Cosmos.ucc.ie> /staff/jabowen>
PHP files are not special
• PHP files do not have to be executable
• They can be regarded as simply HTML files
with some new tags
PHP tags
• In the example just seen, the PHP tag was
• This is the best PHP tag to use – it is the one
which works best if we are also using XML,
because it avoids conflicts with XML Processing
Instructions
• However, you may occassionally see the
following tags being used in other people‟s PHP
code:
…
Variables in PHP
• Variables in PHP are denoted by a dollar
sign followed by the name of the variable.
• A variable name is case-sensitive.
• A valid variable name starts with a letter or
underscore, followed by any number of
letters, numbers, or underscores.
Example Usage of Variables
Greetings
Greetings
Automatic variables in PHP
• One of the main benefits of PHP is that it
provides lots of variables automatically
• Consider, for example, the .php file on the
next slide
• It produces the output on the following two
slides when viewed by MSIE 6.0 and
Netscape 2.0
Example usage of automatic PHP variable
Your browser
Your Browser
You are using
to view this page.
A warning about pre-defined variables
• The way in which PHP supports pre-defined
variables has changed recently
– The way shown on the previous slide is the
newer way
– But there is also an older way
• This will be discussed in a future lecture
Data Types in PHP
• PHP supports eight primitive data types
• There are four scalar types
– boolean
– integer
– floating-point number
– string
• There are two structured types
– array
– object
• There are two special data types
– resource
– NULL
• The programmer does not specify the type of a variable
– a variable‟s type is determined from the context of its usage
Booleans
• The boolean data type admits two values
– true (case-insensitive)
– false (case-insensitive)
• Example usage
$itIsRainingToday = true;
$thePrinterIsBusy = True;
$theQueueIsEmpty = FALSE;
Integers
• Integers can be specified in decimal, hexadecimal
or octal notation, optionally preceded by a sign
– In octal notation, the number must have a leading 0
– In hexadecimal notation, the number must have a
leading 0x.
• Examples
$a = 1234; # decimal number
$a = -123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x1B; # hexadecimal number (equivalent to 27 decimal)
• The maximum size of an integer is platform-
dependent, but usually it‟s 32 bits signed – about
2,000,000,000
• PHP does not support unsigned integers.
Floating Point Numbers
• These can be specified using any of these forms:
$a = 1.234;
$a = 1.2e3;
$a = 7E-10;
• The maximum size of a float is platform-
dependent, although most support a maximum of
about 1.8e308 with a precision of roughly 14
decimal digits
Strings
• A string literal can be specified in three different
ways:
– single quoted
– double quoted
– heredoc syntax
Single-quoted Strings
• In single-quoted strings, single-quotes and
backslashes must be escaped with a
preceding backslash
• Example usage
echo 'this is a simple string';
echo 'You can embed newlines in strings,
just like this.';
echo „Douglas MacArthur said "I\'ll be back” when leaving the Phillipines';
echo 'Are you sure you want to delete C:\\*.*?';
Double-quoted Strings
• In double-quoted strings,
– variables are interpreted to their values, and
– various characters can be escaped
• \n linefeed
• \r carriage return
• \t horizontal tab
• \\ backslash
• \$ dollar sign
• \” double quote
• \[0-7]{1,3} a character in octal notation
• \x[0-9A-Fa-f]{1,2} a character in hexadecimal notation
Heredoc Strings
• Heredoc strings are like double-quoted strings without the
double quotes
• A heredoc string is delimited as follows
– The string is preceded by ] value, … )
• A key is either a string or a non-negative
integer
• A value can be anything
Specifying an array (contd.)
• Format of array specification
array( [key =>] value, ... )
• Here is a hash array:
$mothers =
array (“tom"=>“mary", “mick"=>“ann", “bill"=>“orla");
• Implicit indices are integers, starting at 0
– Here is an ordinary array (indexed by integers,
starting at 0):
$places = array (“Cork”, “Dublin”, “Galway”);
Specifying an array (contd.)
• If an explicit integer index is followed by
implicit indices, they follow on from the
highest previous index
– Here is an array indexed by integers 1, 2, 3
$places = array (1 => “Cork”, “Dublin”, “Galway”);
– Here is an array indexed by integers 1, 5, 6
$places = array (5=> “Cork”, 1 => “Dublin”, “Galway”);
Specifying an array (contd.)
• A two-dimensional hash array
$parents =
array ( “tom” => array (“father” => “bill”, “mother”=> “mary”),
“dave” => array(“father” => “tom”, “mother” => orla”)
);
• A two-dimensional ordinary array
$heights =
array ( array (10,20),
array(100,200)
);
Array Example 1
Array Demo
Array Demo
'Paris','Ireland'=>'Dublin');
echo 'The capital of Ireland is ';
echo $capital['Ireland'];
?>
Array Example 2
Array Demo
Array Demo
'Paris', „Ireland'=>'Dublin');
echo "The various capitals are\n";
foreach ($capital as $city) { echo "$city"; };
echo ""
?>
Array Example 3
Array Demo
Array Demo
'Paris', 'Ireland'=>'Dublin');
echo "The various capitals are\n";
foreach ($capital as $country => $city)
{ echo "The capital of $country is $city"; };
echo ""
?>
Array Example 4
Details about Fred
Details about Fred
2, "Tom"=> 45);
$parents = array ("Fred" => array("father" => "Tom", "mother"=>"Mary"));
print " Fred's age is ";
print $ages["Fred"];
print ".";
print "His father is ";
print $parents["Fred"]["father"];
print ".";
?>
Array-manupulation functions
• PHP provides a huge set of array-manipulation
functions
• array -- Create an array
• array_change_key_case -- Returns an array with all string keys lowercased or
uppercased
• array_chunk -- Split an array into chunks
• array_count_values -- Counts all the values of an array
• array_diff -- Computes the difference of arrays
• array_filter -- Filters elements of an array using a callback function
• array_flip -- Flip all the values of an array
• array_fill -- Fill an array with values
• array_intersect -- Computes the intersection of arrays
• array_key_exists -- Checks if the given key or index exists in the array
• array_keys -- Return all the keys of an array
• array_map -- Applies the callback to the elements of the given arrays
• array_merge -- Merge two or more arrays
• array_merge_recursive -- Merge two or more arrays recursively
• array_multisort -- Sort multiple or multi-dimensional arrays
• array_pad -- Pad array to the specified length with a value
• array_pop -- Pop the element off the end of array
• array_push -- Push one or more elements onto the end of array
• array_rand -- Pick one or more random entries out of an array
• array_reverse -- Return an array with elements in reverse order
• array_reduce -- Iteratively reduce the array to a single value using a callback function
• array_shift -- Shift an element off the beginning of array
• array_slice -- Extract a slice of the array
• array_splice -- Remove a portion of the array and replace it with something else
• array_sum -- Calculate the sum of values in an array.
• array_unique -- Removes duplicate values from an array
• array_unshift -- Prepend one or more elements to the beginning of array
• array_values -- Return all the values of an array
• array_walk -- Apply a user function to every member of an array
• arsort -- Sort an array in reverse order and maintain index association
• asort -- Sort an array and maintain index association
• compact -- Create array containing variables and their values
• count -- Count elements in a variable
• current -- Return the current element in an array
• each -- Return the current key and value pair from an array and advance the
array cursor
• end -- Set the internal pointer of an array to its last element
• extract -- Import variables into the current symbol table from an array
• in_array -- Return TRUE if a value exists in an array
• array_search -- Searches the array for a given value and returns the
corresponding key if successful
• key -- Fetch a key from an associative array
• krsort -- Sort an array by key in reverse order
• ksort -- Sort an array by key
• list -- Assign variables as if they were an array
• natsort -- Sort an array using a "natural order" algorithm
• natcasesort -- Sort an array using a case insensitive "natural order" algorithm
• next -- Advance the internal array pointer of an array
• pos -- Get the current element from an array
• prev -- Rewind the internal array pointer
• range -- Create an array containing a range of elements
• reset -- Set the internal pointer of an array to its first element
• rsort -- Sort an array in reverse order
• shuffle -- Shuffle an array
• sizeof -- Get the number of elements in variable
• sort -- Sort an array
• uasort -- Sort an array with a user-defined comparison function and maintain
index association
• uksort -- Sort an array by keys using a user-defined comparison function
• usort -- Sort an array by values using a user-defined comparison function
Objects
• PHP supports object-oriented
programming
• The subject is too big to cover here
• But here‟s an example
say_hello();
?>
Resources
• This data type is used for maintaining links
to external resources, such as data bases etc.
• A full treatment is beyond our scope here
The NULL data type
• This data type contains only one value
NULL
• It is case-insensitive
• This is a value which is returned when some
expression has no value
• Example
$capital = array ('France'=>'Paris', 'Ireland'=>'Dublin');
$capitalOfEngland = $capital[„England‟];
• In this case, $capitalOfEngland would get
the value NULL
Changing Data Type
• PHP will, in some circumstances, change
the type of a datum
– For example, it will treat a string of digits as a
number if it finds in an arithmetic expression
• PHP also supports type casting
Automatic Variables (again)
• PHP‟s automatic variables come from the
following sources:
– the Environment
– query expressions in GET requests
– message bodies in POST requests
– cookies
– the Server
CGI environment variables
• CGI environment variables are automatically
available
• Example:
What I know about you
I know some things about you
You are using $_SERVER[„HTTP_USER_AGENT‟] to view this
page.";
echo "You used the $_SERVER[„REQUEST_METHOD‟] request method.";
echo "You used this request URI: $_SERVER[„REQUEST_URI‟].";
echo "You accessed this host URI: $_SERVER[„HTTP_HOST‟].";
echo "You used this protocol: $_SERVER[„SERVER_PROTOCOL‟].";
?>
Form variables (via either GET or POST)
• These are automatically available
• Example Form:
Application Form
Your surname:
Your address:
Please send me the brochure.
• Example Response Generator:
Thank you
Thank you
Thank you,.
We will send our brochure to .
Control Structures – if statements
• if ($a > $b)
echo "a is bigger than b";
• if ($a > $b)
{print "a is bigger than b";
$b = $a;}
• if ($a > $b)
{print "a is bigger than b";}
else {print "a is NOT bigger than b";}
• if ($a > $b)
{print "a is bigger than b";}
elseif ($a == $b)
{print "a is equal to b";}
else {print "a is smaller than b“;}
Example usage
• Example
Your browser
Your Browser
to view this page.
• strstr is a boolean function which checks if
its 2nd argument is a substring of its 1st
• CS 3314 got here on 10 nov 2005
Control constructs -- while
• These are just like their counterparts in C
• $i = 1;
while ( $i 0);
Control constructs -- for
• These are just like their counterparts in C
• for ($i = 1; $i $value)
statement
Jumping in and out of PHP mode
• We can can jump in and out of PHP mode even in
the middle of a PHP block:
You are using Internet Explorer You are not using Internet Explorer
• Instead of using an echo statement to print
something, we jumped out of PHP mode.
• Note that the logical flow of the PHP remains
intact
– Only one of the HTML blocks will be sent to the user.
A FORM and its handler in one file
Application Handler
Your surname:
Your address:
Please send me the brochure.
Thank you, $surname.";
echo " We will write to you at $address.";} ?>
• cs 3314 got here on 13 nov 2005
One request for this resource:
no Query or Message Body
interzone.ucc.ie> telnet student.cs.ucc.ie 80
Trying 143.239.211.125...
Connected to student.cs.ucc.ie.
Escape character is '^]'.
GET http://student.cs.ucc.ie/cs4400/jabowen/php/file012.php HTTP/1.1
Host: student.cs.ucc.ie
Response to request with no query or message body
HTTP/1.1 200 OK
Date: Fri, 08 Feb 2002 11:21:40 GMT
Server: Apache/1.3.20 (Unix) PHP/4.0.6
X-Powered-By: PHP/4.0.6
Transfer-Encoding: chunked
Content-Type: text/html
160
Application Handler
Your surname:
Your address:
Please send me the brochure.
0
Connection closed by foreign host.
interzone.ucc.ie>
Another request – containing a query
interzone.ucc.ie> telnet student.cs.ucc.ie 80
Trying 143.239.211.125...
Connected to student.cs.ucc.ie.
Escape character is '^]'.
GET http://student.cs.ucc.ie/cs4400/jabowen/php/file012.php?surname=doyle HTTP/1.1
Host: student.cs.ucc.ie
Response to request containing a query
HTTP/1.1 200 OK
Date: Fri, 08 Feb 2002 11:31:01 GMT
Server: Apache/1.3.20 (Unix) PHP/4.0.6
X-Powered-By: PHP/4.0.6
Transfer-Encoding: chunked
Content-Type: text/html
88
Application Handler
Thank you, doyle. We will write to you at .
0
Connection closed by foreign host.
interzone.ucc.ie>
Finding out about your PHP environment
• One of the many pre-defined PHP
functions is phpinfo()
Your PHP Environment
• In what follows, notice that mySQL
support is enabled
A mysql database
mysql>
mysql> use cs4400db
mysql> select * from student;
+------------+------+------------+
| name | sex | birth |
+------------+------+------------+
| john brown | m | 1980-01-05 |
| bill brown | m | 1980-11-23 |
+------------+------+------------+
mysql>
A PHP program which displays this database
The Student Database
The Student Database
NameSexPosition
%s%s%s\n",
$myrow[0], $myrow[1], $myrow[2]); } ?>
File upload form
Upload a File
Upload a File
File to Upload:
"Upload File“
File upload script
File Received
File Received
The following file has been received:
, containing bytes
and of MIME type
.
• Normally, when a browser sends HTML
form data in the message body of a POST
request, the value in the CONTENT-TYPE
header is:
application/x-www-form-urlencoded
• The new attribute, enctype, in the FORM
tag tells the browser that it should send the
following value in the CONTENT-TYPE
header:
multipart/form-data
Controlling Headers/Status lines with PHP
Sending Headers in PHP
• You have seen that, if you use the CGI protocol,
you can have complete control over the status line
and headers that are sent in a HTTP response – to
do so, you must use nph files
• PHP does not seem to provide the same level of
control
– For example, it seems to prevent one sending status
lines involving status codes that you have invented
yourself – even though HTTP allows this
• Nevertheless, PHP does enable you to have some
control over status lines and response headers
Sending Headers in PHP (contd.)
• PHP provides a built-in function, header(), which can be
used to set HTTP header lines in a response message
– The function name is mis-leading – it can also, within limits, be
used to control the HTTP status line
• Format:
header ( some-string [, some-boolean]);
• Example calls:
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM‘,false);
• By default, a second header of the same type will replace
an earlier one of the same type
– If false is sent as the optional boolean parameter, the header will
not replace an earlier one of the same type
Sending Headers in PHP (contd.)
• PHP treats two type of call to header() in a special
way
• If you use header() to send a Location: header,
PHP will auatomatgically change the code in the
status line of the response to be 302 (REDIRECT)
• The second special case is any header that starts
with the string, "HTTP/" (case is not significant)
– this will be used, within the limits of predefined
standard values, to control the status line
– header("HTTP/1.0 404 Not Found");
User-authentication in PHP
• The header() function can be used to send headers
requiring authentication
– This will cause a browser to pop up a
username/password/realm dialog window and
– When the values have been provided, send a new
request back to the same page containing the
appropriate information
• This time, some special PHP variables will be set:
$PHP_AUTH_USER,
$PHP_AUTH_PW and
$PHP_AUTH_TYPE
User-authentication in PHP (contd.)
• The code below captures the user’s name and password
• An improved version would check this against the contents of
some file
Hello $PHP_AUTH_USER.";
echo "Your password is $PHP_AUTH_PW "; }
?>
User-authentication in PHP (contd.)
• The PHP_AUTH variables will not be set if external
authentication is enabled for that particular page.
– This is to prevent a script which reveals the password for a page
that was protected through a traditional external mechanism, such
as the .htpasswd mechanism
• In this case, the $REMOTE_USER variable can be used to
identify the externally-authenticated user.
Handling Cookies in PHP
• PHP provides a function called setcookie() which can be used to
send cookies to a browser
– Since cookies are sent in HTTP headers, this function must be
called before any ordinary content (such as HTML) is sent
• Cookies sent from a broswer to a client will be converted into
automatically created variables – just like those that are created
to present data which come in GET and POST requests
Image Handling
• As well as generating dynamic HTML, PHP can generate and
manipulate images