Chapter 12
Chapter 12
Chapter 12
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
In this chapter you will learn . . .
• What is server-side development
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Front End versus Back End
Server-side technologies
provide access to data
sources, handled security,
and allowed web sites to
interact with external
services such as payment
systems.
• JSP (Java Server Pages). JSP uses Java as its programming language and like ASP.NET it uses an explicit
object-oriented approach and is used in large enterprise web systems and is integrated into the J2EE
environment.
• PHP. Like ASP, PHP is a dynamically typed language that can be embedded directly within the HTML
• Python. This terse, object-oriented programming language has many uses, including being used to create web
applications.
• Ruby on Rails. This is a web development framework that uses the Ruby programming language.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Running PHP locally
Installing Apache, PHP, and MySQL for Local Development
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
PHP Language Fundamentals
PHP is a a dynamically typed language (with optional static typing), and
provides classes and functions in a way consistent with other object-oriented
languages such as C++, C#, and Java.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
PHP Tags and comments
PHP code can be embedded directly within an HTML file. However, instead of
having an .html extension, a PHP file will usually have the extension .php.
Code must be contained within an opening <?php tag and a matching closing
?> tag. Code within the <?php and the ?> tags is interpreted and executed,
while any code outside the tags is echoed directly out to the client.
It is very common practice (especially when first learning PHP) for a PHP file
to have HTML markup and PHP programming logic woven together.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
PHP Tag Example
<?php <!DOCTYPE html>
$user = "Randy"; <html>
?> <body>
<!DOCTYPE html> <h1>Welcome Randy</h1>
<html> <p>
<body> The server time is <strong>02:59:09</strong>
<h1>Welcome <?php echo $user; ?></h1> </p>
<p> </body>
The server time is </html>
<?php
LISTING 12.2 Output (HTML) from PHP script in
echo "<strong>";
Listing 12.1
echo date("H:i:s");
echo "</strong>";
?>
</p></body></html>
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
PHP constants
<?php
• A constant can be defined
// uppercase for constants is a programming convention
anywhere but is typically defined define("DATABASE_LOCAL", "localhost");
near the top of a PHP file via the define("DATABASE_NAME", "ArtStore");
define() function. The define() define("DATABASE_USER", "Fred");
define("DATABASE_PASSWD", "F5^7%ad");
function generally takes two // ...
parameters: the name of the // notice that no $ prefaces constant names
constant and its value. Notice that $db = new mysqli( DATABASE_LOCAL,
DATABASE_NAME, DATABASE_USER,
once it is defined, it can be
DATABASE_PASSWD);
referenced without using the $ ?>
symbol.
LISTING 12.3 PHP constants
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Writing to Output
To output something that will be seen by the browser, you can use the echo() function.
echo("hello");
echo "hello"; //alternate version (no parenthesis)
Strings can be appended together using the concatenate operator, which is the period
(.) symbol. Consider the following code:
$username = "Ricardo";
echo "Hello " . $username;
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
PHP quote and concatenation approaches
<?php
$firstName = "Pablo"; /* Example two: These two lines are also equivalent. Notice that
$lastName = "Picasso"; you can use either the single quote symbol or double quote
symbol for string literals. */
/*Example one:
These two lines are equivalent. Notice that you can reference echo "<h1>";
PHP variables within a string literal defined with double quotes. echo '<h1>’;
The resulting output for both lines is:
<em>Pablo Picasso</em>*/ /* Example three: These two lines are also equivalent. In the
second example, the escape character (the backslash) is used to
echo "<em>" . $firstName . " ". $lastName. "</em>"; embed a double quote within a string literal defined within
echo "<em> $firstName $lastName </em>"; double quotes. */
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
printf
The printf() function is derived from the C
programming language is nearly ubiquitous
in programming, appearing in many
languages including Java, MATLAB, Perl,
Ruby, and others.
• if . . . else
• switch . . . case
• for
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
If…else
The syntax for conditionals in // if statement
PHP is identical to that of if ( $hourOfDay > 6 && $hourOfDay < 12) {
$greeting = "Good Morning";
JavaScript.
}
else if ($hourOfDay == 12) { // optional else if
The condition to test is contained
$greeting = "Good Noon Time";
within () brackets with the
}
body contained in {} blocks. else { // optional else branch
Optional else if statements $greeting = "Good Afternoon or Evening";
can follow, with an optional }
else ending the branch.
LISTING 12.7 Conditional snippet of code using if . . . else
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
PHP and HTML in the same script
<?php if ($userStatus == "loggedin") { ?> <?php
<a href="account.php">Account</a> // equivalent
<a href="logout.php">Logout</a> if ($userStatus == "loggedin") {
<?php } else { ?> echo '<a href="account.php">Account</a> ‘;
<a href="login.php">Login</a> echo '<a href="logout.php">Logout</a>';
<a href="register.php">Register</a> }
<?php } ?> else {
echo '<a href="login.php">Login</a> ‘;
echo '<a href="register.php">Register</a>';
}
?>
LISTING 12.8 Combining PHP and HTML in the same script
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
switch . . . case
The switch statement is similar to a series of if ... else statements.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
while and do . . . while
In the while loop, the condition is tested at the beginning of the loop; in the do
... while loop the condition is tested at the end of each iteration of the loop.
$count = 0; do {
while ($count < 10) { echo $count;
echo $count; // this one increments the count by 2
$count++; each time
} $count = $count + 2;
$count = 0; } while ($count < 10);
LISTING 12.10 The while loops
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
For loops
The for loop in PHP has the same syntax as the for loop in JavaScript that we
examined in Chapter 8. For loops contain the same loop initialization,
condition, and postloop operations as in JavaScript.
// this one increments the value by 5 each time // this one increments the count by 1 each time
for ($count=0; $count < 100; $count+=5) { for ($count=0; $count < 10; $count++) {
echo $count; echo $count;
} }
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Alternate Syntax for Control Structures
<?php if ($userStatus == "loggedin") : ?>
PHP has an alternative syntax <a href="account.php">Account</a>
for most of its control <a href="logout.php">Logout</a>
structures. <?php else : ?>
<a href="login.php">Login</a>
In this alternate syntax, the <a href="register.php">Register</a>
<?php endif; ?>
colon (:) replaces the opening
LISTING 12.12 Alternate syntax for control structures
curly bracket, while the closing
brace is replaced with endif;,
endwhile;, endfor;,
endforeach;, or endswitch;.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Include Files
PHP has the ability to include or
insert content from one file into
another. Include files provide a
mechanism for reusing both
markup and PHP code
include "somefile.php";
include_once "somefile.php";
require "somefile.php";
require_once "somefile.php";
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Functions
Just like with JavaScript, a function in PHP contains a small bit of code that
accomplishes one thing.
• A built-in function is one of the functions that come with the PHP
environment (or with one of its extensions).
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Function Syntax
Functions can return values to the caller, or not return a value.
function getNiceTime(){
return date("H:i:s");
}
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Return Type Declaration
PROTIP
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Invoking a Function
To invoke or call a function you must use its name with the () brackets. Since
getNiceTime() returns a string, you can assign that return value to a variable,
o echo that return value directly, as shown in the following example:
$output = getNiceTime();
echo getNiceTime();
If the function doesn’t return a value, you can just call the function:
outputFooterMenu();
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Parameters
Parameters are the mechanism by which values are passed into functions. To
illustrate, let us write another version of getNiceTime() that takes an integer
as a parameter to control whether to show seconds. You will call the
parameter showSeconds
function getNiceTime($showSeconds) {
if ($showSeconds==true)
return date("H:i:s");
else
return date("H:i");
}
LISTING 12.16 A function with a parameter
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Parameter Default Values
In PHP you can set parameter default values for any parameter in a
function. However, once you start having default values, all subsequent
parameters must also have defaults.
function getNiceTime($showSeconds=true) {
if ($showSeconds==true)
return date("H:i:s");
else
return date("H:i");
}
LISTING 12.17 A function with a parameter default
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Passing Parameters by Reference
By default, arguments
passed to functions are
passed by value in PHP.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Parameter-type declaration
It is now possible to require that a particular parameter be of a particular type.
To add a type to a parameter, add a type specification (int, float, string, bool,
callable, or any class name you have defined) before the parameter name.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Variable Scope within Functions
All variables defined within a function have function scope, meaning that
they are only accessible. within the function. It might be surprising though to
learn that, unlike JavaScript, any variables created outside of the function in
the main script are unavailable within a function.
PHP does allow variables with global scope to be accessed within a function
using the global keyword, though generally speaking, its usage is
discouraged.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Arrays
Unlike most other programming languages (including JavaScript), in PHP an
array is actually an ordered map, which associates each value in the array
with a key.
This allows you to use arrays in PHP in a manner similar to other languages’
arrays, but you can also use them like other languages’ collection classes.
• Array values, unlike keys, are not restricted to integers and strings. They
can be any object, type, or primitive supported in PHP.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Defining an Array
The following declares an empty array named days:
$days = array();
To define the contents of an array as strings for the days of the week, you declare it
using either of two following syntaxes:
$days = array("Mon","Tue","Wed","Thu","Fri");
$days = ["Mon","Tue","Wed","Thu","Fri"]; // alternate syntax
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Accessing an Array
• Explicit control of the keys and values opens the door to keys that do not
start at 0, are not sequential, and that are not even integers (but rather
strings).
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Multidimensional Arrays
$month = array(
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri")
);
LISTING 12.22 Multidimensional arrays
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Multidimensional Arrays (ii)
$cart = [];
$cart[] = array("id" => 37,
"title" => "Burial at Ornans",
"quantity" => 1);
$cart[] = array("id" => 345,
"title" => "The Death of Marat",
"quantity" => 1);
$cart[] = array("id" => 63,
"title" => "Starry Night",
"quantity" => 1);
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Multidimensional Arrays (iii)
$stocks = [
["AMZN", "Amazon"],
["APPL", "Apple"],
["MSFT", "Microsoft"]
];
$aa = [
"AMZN" => ["Amazon", 234],
"APPL" => ["Apple", 342],
"MSFT" => ["Microsoft", 165]
];
$bb = [
"AMZN" => ["name" =>"Amazon", "price" => 234],
"APPL" => ["name" => "Apple", "price" => 342],
"MSFT" => ["name" => "Microsoft", "price" => 165]
];
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Iterating through an Array
// while loop // iterating through the values
$i=0; foreach ($forecast as $value) {
while ($i < count($days)) { echo $value . "<br>";
echo $days[$i] . "<br>"; }
$i++;
} // iterating through the values AND
the keys
// for loop foreach ($forecast as $key => $value){
for ($i=0; $i<count($days); $i++) { echo "day[" . $key . "]=" . $value;
echo $days[$i] . "<br>"; }
}
LISTING 12.23 Iterating through an array using LISTING 12.24 Iterating through an associative
while, do while, and for loops array using a foreach loop
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Adding and Deleting Elements
In PHP, arrays are dynamic, that is, they can grow or shrink in size.
A new element can be added to the end of any array using empty square
brackets after the array name, as follows:
$days[] = "Sun";
You can also explicitly delete array elements using the unset() function
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Checking if a Value Exists
$oddKeys = array(1 => "hello", 3 => "world", 5 => "!");
To check if a value if (isset($oddKeys[0])) {
// The code below will never be reached since
exists for a key, you
//$oddKeys[0] is not set!
can therefore use the echo "there is something set for key 0";
isset() function, which }
returns true if a value
if (isset($oddKeys[1])) {
has been set, and false // This code will run since a key/value pair was defined
otherwise //for key 1
echo "there is something set for key 1, namely ". $oddKeys[1];
}
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Classes and Objects
Classes outline properties and
methods like a blueprint. Each
variable created from a class is
called an object or instance,
and each object maintains its
own set of variables, an
behaves (largely) independently
from the class once created.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Defining and instantiating Classes
The PHP syntax for
defining a class uses the
class keyword followed
by the class name and { } class Artist {
braces. public $firstName;
public $lastName;
public $birthDate;
public $birthCity;
public $deathDate;
}
LISTING 12.27 A simple Artist class
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Properties
instantiate objects using
the new keyword
$picasso = new Artist();
$picasso = new Artist();
$dali = new Artist(); $dali = new Artist();
$picasso->firstName = "Pablo";
You can access and $picasso->lastName = "Picasso";
modify the properties of $picasso->birthCity = "Malaga";
each object separately $picasso->birthDate = "October 25 1881";
using its variable name $picasso->deathDate = "April 8 1973";
and an arrow (->),
LISTING 12.28 Instantiating and using objects
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Constructors
You should therefore define
constructors, which lets class Artist {
you specify parameters // variables from previous listing still go here
during instantiation to ...
initialize the properties within function __construct($firstName, $lastName,
a class right away. $city, $birth,$death=null) {
$this->firstName = $firstName;
$this->lastName = $lastName;
In PHP, constructors are
$this->birthCity = $city;
defined as functions with the $this->birthDate = $birth;
name __construct(). $this->deathDate = $death;
}
(Note: there are two }
underscores_ before the
word construct.) LISTING 12.29 A constructor added to the class definition
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Methods
class Artist {
public function outputAsTable() {
Methods define the tasks $table = "<table>";
each instance of a class can $table .= "<tr><th colspan='2'>";
perform and are useful since $table .= $this->firstName . " " . $this->lastName;
they associate behavior with $table .= "</th></tr>";
objects. $table .= "<tr><td>Birth:</td>";
$table .= "<td>" . $this->birthDate;
Call the method as follows: $table .= "(" . $this->birthCity . ")</td></tr>";
$table .= "<tr><td>Death:</td>";
$picasso = new Artist(. . .) $table .= "<td>" . $this->deathDate . "</td></tr>";
$table .= "</table>";
echo $picasso->outputAsTable(); return $table;
}
}
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Sample ways to diagram a class using UML
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Visibility
The visibility of a
property or method
determines the
accessibility of a class
member
A property or method
and can be set to
public, private, or
protected
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Static Members
class Artist {
public static $artistCount = 0;
Static member is a property or public $firstName;
method that all instances of a public $lastName;
class share. public $birthDate;
public $birthCity;
public $deathDate;
To illustrate how a static function __construct($firstName, $lastName,
member is shared between $city,$birth, $death=null) {
instances of a class, we will add $this->firstName = $firstName;
$this->lastName = $lastName;
the static property artistCount
$this->birthCity = $city;
to our Artist class, and use it to $this->birthDate = $birth;
keep a count of how many Artist $this->deathDate = $death;
objects are currently self::$artistCount++;
}
instantiated }
LISTING 12.31 Class definition modified with static members
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
A static property in UML
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Inheritance
Inheritance enables you to create new PHP classes that reuse, extend, and
modify the behavior that is defined in another PHP class.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
UML showing inheritance
Both references below work because it is as
if the base class public members are defined
within the subclass.
$p = new Painting();
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
$_GET and $_POST Superglobal Arrays
PHP uses special predefined associative arrays called superglobal arrays that allow
the programmer to easily access HTTP headers, query string parameters, and other
commonly needed information
$GLOBALS Array for storing data that needs $_POST Array of query string data passed to the server
superglobal scope via the HTTP header
$_COOKIES Array of cookie data passed to page via $_REQUEST Array containing the contents of $_GET,
HTTP request $_POST, and $_COOKIES
$_ENV Array of server environment data $_SESSION Array that contains session data
$_FILES Array of file items uploaded to the server $_SERVER Array containing information about the
request and the server
$_GET Array of query string data passed to the server
via the URL
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Illustration of flow into $_GET array
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Illustration of flow into $_POST array
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Determining If Any Data Sent
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ( isset($_POST["uname"]) && isset($_POST["pass"]) )
{
// handle the posted data.
echo "handling user login now ...";
echo "... here we could redirect or authenticate ";
echo " and hide login form or something else";
}
}
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Accessing Form Array Data
Sometimes in HTML forms, you might have multiple values associated with a single
name. Unfortunately, if the user selects more than one day and submits the form, the
$_GET['day'] value in the superglobal array will only contain the last value from the list
that was selected.
To overcome this limitation, you must change the HTML in the form. In particular, you
will have to change the name attribute for each checkbox from day to day[]
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Sanitizing Query Strings
One of the most important things to remember about web development is that
you should actively distrust all user input.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Redirecting Using Location Header
One of the most common uses of this
function in PHP is to redirect. For
instance, a PHP page might redirect
to an error page when an expected
querystring parameter is missing
<?php
if (! isset($_GET['id']) {
header("Location: error.php");
}
...?>
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Setting the Content-Type Header
The Content-Type HTTP header is used to tell the browser what type of
content (using a MIME type) it is receiving in the response.
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved
Key Terms
array concatenation instance parameter default sanitizing user
values inputs
array keys constant instantiate
parameters server-side
array values constructors local repository includes (SSI)
passed by
associative arrays data types loosely typed reference subclass
Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved