PHP 03
PHP 03
What is PHP?
689
• PHP stands for PHP Hypertext Processor — A recursive
definition!!.
• PHP is a server-side scripting language that is embedded in
a web page or can be run as script (much Like Perl) from the
command line (Full support since version 4.3)
JJ
II
J
I
Back
Close
PHP Characteristics
The main characteristics of PHP are:
• PHP is web-specific and open source
• Scripts are embedded into static HTML files
• Fast execution of scripts
690
• Fast access to the database tier of applications
• Supported by most web servers and operating systems
• Supports many standard network protocols libraries available for IMAP, NNTP,
SMTP, POP3,
• Supports many database management systems libraries available for UNIX DBM,
MySQL, Oracle,
• Dynamic Output any text, HTML XHTML and any other XML file.
• Also Dynamic Output images, PDF files and even Flash movies
• Text processing features, from the POSIX Extended or Perl regular expressions JJ
to parsing XML documents. II
• A fully featured programming language suitable for complex systems J
development I
Back
Close
What can PHP do?
As we have just said PHP is a fully featured programming language
so it can do just about anything.
• Mac OS X,
• Windows
• RISC OS,
• and probably others.
PHP already installed on School’s Web Server
Perl:
• Interpreted language optimized to process text files — Ideal for 694
CGI use.
• Using a Perl script as a CGI means that when an online form
calls the script to be processed, the web server will load the Perl
script, and pipe the output of the script back to the user, on its
web browser.
• Simple syntax, similar to C
• Includes advanced functionality through numerous packages
(CPAN) JJ
II
J
I
Back
Close
PHP v Perl (Cont.)
PHP :
• Server-side scripting language embedded in HTML pages.
• Processed by the web server when the HTML page is loaded.
695
• PHP code included in special HTML tags which are parsed by
the web server.
• Syntax is different from Perl (but not that much different)
• PHP also has some very advanced functions.
JJ
II
J
I
Back
Close
Advantages of Perl/PHP
Perl has a lot of advantages:
• General purpose language — functions to do nearly everything.
• Perl has modules that can be downloaded and loaded in a Perl
script. 696
JJ
II
J
I
Back
Close
Advantages of Perl/PHP (Cont.)
PHP also has some advantages:
• It is included inside HTML pages.
This means that:
– All your work can be done in the same directory, and 697
JJ
II
J
I
Back
Close
Disadvantages of Perl/PHP
Perl:
• Management of simple scripts is more difficult than PHP:
– Scripts need to be loaded separately from the HTML pages.
– Typically scripts also be kept in a special directory — E.g. 698
cgi-lib.pl,
• PHP integrates itself very well in HTML files —
so scripts don’t need to be loaded from a separate location.
• However, if the PHP code is complex it can lead to a complex
mixture of code on the page.
JJ
II
J
I
Back
Close
Disadvantages of Perl/PHP (Cont.)
PHP:
• Great for simple Dynamic web page processing,
• Not so great for more complex tasks
699
– Harder to parse/understand and maintain lots of code mixed
in with web page (see above).
– Not as general purpose as Perl.
• PHP requires that the server is configured to parse PHP files.
– Perl similar but both now widely supported.
• Also, PHP files need to be parsed by the server at each load, so
they should not be used in files that don’t need to be processed.
– Perl similar but both slightly less overhead. JJ
II
J
I
Back
Close
Examples of Uses of Perl/PHP
Neither Perl Nor PHP best for all web tasks:
• Horses for Courses
• Search Engines,
• Data processing,
• Heavy File access etc.
• Heavy Database Access/Usage
• PHP files are simply text files — use any text editor, integrate
with HTML
• File has extension .php 701
JJ
II
J
I
Back
Close
Using PHP on COMSC Web Server
• COMSC Web server preconfigured to run PHP
• Use Unix web space (public html or project html)
• Create file on Macs (or PCs) ftp or upload via file sharing.
• Store files with .php extension 702
JJ
II
J
I
Back
Close
Including PHP in a Web Page
There are 4 ways of including PHP in a web page
1. <?php echo("Hello world"); ?>
2. <script language = "php">
echo("Hello world"); 703
</script>
3. <? echo("Hello world"); ?>
4. <% echo("Hello world"); %>
JJ
II
J
I
Back
Close
A Simple PHP Script Example
Here is first complete PHP script which is embedded in HTML:
• We create a level one header with the PHP output text.
• This file is called hello.php:
705
<html>
<head>
<title>Hello world</title>
</head>
<body>
<h1><?php echo("Hello world"); ?></h1>
</body>
<html>
JJ
II
J
I
Back
Close
Basic PHP
Comments
PHP supports three types of comments:
JJ
II
J
I
Back
Close
Shell style comments :
• Denoted by #, like Perl,
• End of comment’s range is similar to Perl
– Except that the end of PHP section code tag (?>) delimits
the end of comment as well as
707
– The end of the line, e.g.:
<?php
# This is a comment
?>
E.g.:
<?php
//This is a comment
?> 708
C style comments : denoted by start /*,and end */, you can use
these to create block of statements.
E.g.:
<?php
/* comments start here
continue on this line
JJ
any php commands are ignored
II
<?php echo "ignored"?>
J
comments end here */
I
?>
Back
Close
Variables
Variables start with the $ symbol (like Perl).
E.g.:
$myInteger = 3; 709
$myString = "Hello world";
$myFloat = 3.145;
JJ
II
J
I
Back
Close
PHP Data Types
Data types are not explicitly defined:
• Variable type is determined by assignment.
• Different to Perl.
• Strings can be defined with single (’) and double (") quotes.
710
– Rules for Strings as in Perl.
• PHP has a boolean type:
Defined as false
– An integer or float value of 0 or
– The keyword false
– The empty string ‘‘’’ or the string ‘‘0’’
– An empty array or object
– The NULL value
Defined as true
– Any non-zero integer or float value
JJ
– The keyword true II
• Standard operators with standard syntax applied to variables
J
I
Back
Close
Arrays
$myArray[0] = "Apples";
$myArray[1] = "Bananas";
show($food);
JJ
II
J
I
Back
Close
Local Variables
Variables defined in a function are simply local to that function.
E.G.:
716
function dummy($val) {
$local_val = $val;
return $local_val;
}
$a = 3;
$b = dummy($a); # Wasted op?
$c = $local_val; # Illegal op.
JJ
II
J
I
Back
Close
Variable Scope Example: What happens here?
$a = 3;
what();
echo "a = $a\n";
Is variable $a global/local?
JJ
What is the output of both echo(..)s —- Is it 4? II
Answer: NO it is 1 and then 3! J
I
We actually have two variables called $a!! Back
Close
Scope Example Explained
$a = 3;
function what() {
++$a;
echo "a = $a\n"; 718
}
what();
echo "a = $a\n";
In PHP:
• The variable $a in the function what() is different to outside
variable $a
• Not recommended programming practice to have two variables JJ
of the same name. II
• So the local function prints the value 1 whilst J
I
• The outer prints 3.
Back
Close
Global Variables
So how do we share global values with a function?
• You must declare a variable inside a function as global
function what() {
global $a;
++$a;
echo "a = $a\n";
}
JJ
what();
II
echo "a = $a\n";
J
I
Now the output is 4 at both prints. Back
Close
Flow-Control Statements
PHP provides the standard Flow-controls statements
if, if/else
switch
720
while
for
JJ
II
J
I
Back
Close
Regular Expressions in PHP
• Syntax is identical to those found in Perl (and JavaScript)
• Use PHP function calls however to action a Regular Expression.
• Having created a pattern, we use one of the following functions:
preg match, 721
preg match all,
preg replace,
preg split
JJ
II
J
I
Back
Close
Regular Expressions in PHP Example
For example, regexp.php:
<?php
$test = "This is a Test";
JJ
II
J
I
Back
Close
PHP Regular Expression Example Explained
The function preg match():
• Can take just two parameters as well: E.g.
if (preg_match($pattern,$test) {
echo("Match Found\n"); 723
}
• However in this more complex example we use the parenthesis
as memory feature of regular expressions.
• The $matches parameter is used to store the results of matches
in the brackets
• The (\ws) matches any word character followed by a letter s.
• The two matches are separated by a single space \s
• This first element of $matches stores to complete pattern match: JJ
is is II
J
• The next two elements are the sub matches (delimited by
I
parenthesis): two times is
Back
Close
Some Practical PHP Examples
A 1 line PHP Script
724
Here a simple 1 line PHP script, phpinfo.php:
<?php phpinfo() ?>
It prints out information on the PHP system currently running:
JJ
II
J
I
Back
Close
A 1 line PHP Script (Cont.)
<?php phpinfo() ?>
JJ
II
J
I
Back
Close
Handling HTML Forms
Handling forms could not be much easier than in PHP:
• Variables are automatically initialised by PHP from the
name/value pairs passed in by a HTTP request
• Variables are given the same name as the name of the form item 726
JJ
II
J
I
Back
Close
A Simple PHP/HTML Form Processing Example
Lets Consider the Following HTML Form Source, form1.html:
<html> <head>
<title>Form 1</title>
</head>
<body>
<form name="whoAreYou" method="GET" 727
action="http://www.cs.cf.ac.uk/user/Dave.Marshall/form1.php">
<h2>Who are you?</h2>
<h4>Name:<input type="text" name="username"></h4>
<h4>Address:<input type="text" name="address"></h4>
<input type="submit" value="Send">
</form>
</body> </html>
728
JJ
II
J
I
Back
Close
A Simple PHP/HTML Form Processing Example (Cont.)
The PHP which processes this is very simple, form1.php:
<html>
<head>
<title>form1.php</title>
</head>
<body> 729
<h2>Your name is: <?php echo($username); ?></h2>
<h2>Your address is: <?php echo($address); ?></h2>
</body>
<html>
JJ
II
J
• Note that we simply access the $username and $address I
variables in PHP. Back
Close
Creating and Processing Forms in One PHP file
You can have the action of form self-reference the page that
created the form, This:
730
• Keeps all form processing in one file
• Is excellent for Web page develop and upkeep if:
– Small PHP Scripts
– Not too many fragments of PHP in single document.
• Example: Highlights many good features of PHP
JJ
II
J
I
Back
Close
Forms and Processing Forms in one PHP/HTML File Example
Consider the following example, a Pound to Euro converter,
pound2euro.php :
<html>
<head>
<title>Pound to Euro Converter</title>
</head> 731
<body>
<h1>Pound to Euro Converter</h1>
<?php JJ
$euro = (float) $gbpound* 1.57;
printf("%5.2f Pounds is %5.2f Euros", II
(float) $gbpound, (float) $euro); J
?>
</body>
I
</html> Back
Close
Forms and Processing Forms in one PHP/HTML File Example
(Cont.)
The output looks like this:
732
JJ
II
J
I
Back
Close
Forms and Processing Forms in one PHP/HTML File Example
Explained
One new PHP point to note:
• PHP has a variety of special variables — a bit like Perl.
• $ SERVER[’PHP SELF’] is an associative array that holds 733
information about the server that runs the script.
• PHP SELF refers to the current PHP page that is running and set
the ACTION attribute:
– Makes for portable code to use this
– Can change file name and it still self-references the page
• Much better than and explicit URL to the page
• Need to print the elements to form:. JJ
– Use formatted printf — syntax as in Perl, C/C++ II
J
I
Back
Close
Sending Email from PHP
Again this is a relatively simple task in PHP:
• The mail() function allows your scripts to send email.
For example:
<html> 734
<head>
<title>Email</title>
</head>
<body>
<?php
$to = "[email protected]";
$subject = "PHP is Great";
$body = "Hello how are you goodbye";
$headers = "From: [email protected]\r\n";
$sent = mail($to, $subject, $body, $headers);
if($sent)
echo "Mail sent to $to"; JJ
else II
echo "Error sending mail"; J
?>
</body> I
</html> Back
Close
Sending Email from PHP Example Explained
JJ
II
J
I
Back
Close
Dates in PHP
PHP has many functions for manipulating dates and times.
• The date(date string) function can be used
– To extract date information out in a variety of formats
depending on parameters set in the date string). 736
• The date string, date string), may have the following formats
JJ
II
J
I
Back
Close
Date String Formats
Character Meaning
a Display ”am” or ”pm”
A Display ”AM” or ”PM”
B Swatch Internet time
d day of the month, 2 digits with leading zeros; i.e. ”01” to ”31”
D day of the week, textual, 3 letters; e.g. ”Fri”
F month, textual, long; e.g. ”January”
g hour, 12-hour format without leading zeros; i.e. ”1” to ”12”
G hour, 24-hour format without leading zeros; i.e. ”0” to ”23” 737
h hour, 12-hour format; i.e. ”01” to ”12”
H hour, 24-hour format; i.e. ”00” to ”23”
i minutes; i.e. ”00” to ”59”
I (capital i) ”1” if Daylight Savings Time, ”0” otherwise.
j day of the month without leading zeros; i.e. ”1” to ”31”
l (lowercase ’L’) day of the week, textual, long; e.g. ”Friday”
L boolean for whether it is a leap year; i.e. ”0” or ”1”
m month; i.e. ”01” to ”12”
M month, textual, 3 letters; e.g. ”Jan”
n month without leading zeros; i.e. ”1” to ”12”
O Difference to Greenwich time in hours; e.g. ”+0200”
r RFC 822 formatted date;
e.g. ”Thu, 21 Dec 2000 16:01:07 +0200” (added in PHP 4.0.4)
s seconds; i.e. ”00” to ”59”
S English ordinal suffix for the day of the month, 2 characters;
i.e. ”st”, ”nd”, ”rd” or ”th”
t number of days in the given month; i.e. ”28” to ”31”
T Timezone setting of this machine; e.g. ”EST” or ”MDT”
U seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
w day of the week, numeric, i.e. ”0” (Sunday) to ”6” (Saturday)
W ISO 8601 week number of year, weeks starting on Monday
Y
(added in PHP 4.1.0)
year, 4 digits; e.g. ”1999” JJ
y year, 2 digits; e.g. ”99”
z
Z
day of the year; i.e. ”0” to ”365”
timezone offset in seconds (i.e. ”-43200” to ”43200”).
II
The offset for timezones west of UTC is always
negative, and for those east of UTC is always positive. J
I
Back
Close
Simple PHP Date Example
The following PHP sets the background colour to blue on Tuesdays,
tuesday.php
<?php
if(date("D") == "Tue") $colour = "blue";
738
else $colour = "red";
?>
<html>
<head>
<title>Welcome</title>
</head>
<body bgcolor = <?php echo($colour) ?>>
<h1>Welcome</h1>
</body>
</html> JJ
• Here we simply get day by setting the date string to “D” II
J
• if sets up the $colour variable accordingly I
• echo $colour to set body background colour bgcolor. Back
Close
Another Date Example
xmas.php prints out the current date and works out how long it is
to Christmas:
<html>
<head>
<title>Dates: Days to Christmas</title>
</head> 739
<body>
<h1>Dates: Days to Christmas</h1>
<p>
Today is:<br>
<?php
echo(date("l dS F, Y"));
?>
</p>
<p> There are:
<?php
$daysgone = date("z");
$daystoxmas = 358 - $daysgone; JJ
echo($daystoxmas);
?> days to Christmas</p> II
J
<p><b> Better get shopping now!!!!</b></p>
</body>
I
</html> Back
Close
Xmas Date Example Sample Output
When run the following output is produced in a Web browser:
740
JJ
II
J
I
Back
Close
Xmas Date Example Sample Explained
Things to note in the above xmas.php code:
• We use the date() function twice
• Firstly we print out the date in a fancy format as can be seen in
the screenshot of the display above. 741
• The format string "l dS F, Y" cause the long day of the week,
day of the month with ordinal Suffix followed by a (verbatim)
comma, followed a 4-digit Year.
• Secondly date() call loads a variable with the number of days
gone in the year so far.
• Simple to compute days to go to xmas and format HTML output
JJ
Other date functions include:
II
getdate(), localtime(), mktime(), time() J
I
Back
Close
Cookies and PHP
• A cookie is a text string stored on the client machine by your
script (to track users and manage transactions)
• Cookies are automatically returned (by the client), and can be
accessed using a variable of the same name
742
• The following script reads and displays a cookie, and sets it with
a new value (string) that was passed to the script as a parameter.
• The cookie will expire after 20 minutes (1200 seconds)
<?php setCookie("CookieTest", $val, time()+1200); ?>
<html>
<head><title>Welcome</title></head>
<body>
<?php echo("<h2>The cookie is: $CookieTest</h1>
</body>
</html> JJ
II
J
I
Back
Close
Database Connections in PHP
To complete our brief introduction to PHP lets see how easy it is to
connect to a database.
• PHP can connect to a variety of databases
• We will use MySQL which is available in dept. 743
+--------+----------------+
| toy_id | toy_name |
+--------+----------------+
| 1 | Woody |
| 2 | Buzz Lightyear |
| 3 | Emperor Zurg |
| 4 | Bullseye |
+--------+----------------+
4 rows in set (0.00 sec)
JJ
II
J
I
Back
Close
MySQL Example: PHP Database Querying
Now to the PHP side to query the database and display results on
screen, toys1.php:
<h2>Toys for sale</h2>
<pre>
<?php
// open database connection 748
$connection
= mysql_connect("localhost", "scmxx", "password");
// select the database called "toyshop"
mysql_select_db("toyshop", $connection)
or die("Failed!");
// run the query on the database
$result
= mysql_query("SELECT * FROM toys", $connection);
749
JJ
II
J
I
Back
Close
MySQL Example: PHP Database Query Example Explained
Querying the database
750
1. Connect to the DBMS (MySQL)
2. Select the database required
3. Run the query
4. Retrieve a row of results
5. Process the attribute values
6. Close the DBMS connection
JJ
II
J
I
Back
Close
1. Connect to the DBMS (MySQL)
• Connect to the DBMS using mysql connect()
• parameters:
– The hostname of the DBMS server to use
– The username of a user having access to the database 751
• Return value
– Nothing
– Note the die() function to get out if we cant select the database
— similar to Perl.
mysql_select_db("toyshop", $connection)
or die("Failed!");
• Return value
– A result set handle - to retrieve the output (result set) of the
query
$result
= mysql_query("SELECT * FROM toys",
$connection);
or
$query = "SELECT * FROM toys"; JJ
$result = mysql_query($query, $connection);
II
J
I
Back
Close
4. Retrieve a row of results
• Retrieve a row of results using mysql fetch row()
• Parameters
– The result set handle (obtained in step 3)
• Return value 754
– The next row of the result set, or false when no more data is
available.
• Use a while loop to retrieve the rows
while($row = mysql_fetch_row($result)) {
// extract attribute values
// (step 5) and process
}
JJ
II
J
I
Back
Close
5. Extract attribute values
• Extract attribute values using mysql num fields()
• Parameters:
– The result set handle (obtained in step 3)
• Return value 755
JJ
II
J
I
Back
Close
6. Close the DBMS connection
• Close the DBMS connection using mysql close()
• parameters:
– The connection handle to the DBMS (obtained in step 1)
• Return value 756
– nothing
mysql_close($connection);
JJ
II
J
I
Back
Close
Command Line PHP
Command Line PHP on COMSC Computers
757
You can use Command Line PHP on:
• UNIX web server hosts (sentinel andblazon) only.
• Mac OS X machines
Type man php from the command line to find out more.
JJ
II
J
I
Back
Close
Running PHP Scripts from the Command Line (Cont.)
• 2. Make the php file an executable script
– (Similar to Perl) Make the first line of the script
#!/usr/local/php/bin/php -q
759
(The -q option forces php to inhibit HTTP headers)