Introduction to Server-
Side Development
with PHP
Chapter 8
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Textbook to be published by Pearson ©
Ed2015
in early
Pearson
2014
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
http://www.funwebdev.com
Objectives
1 Server-Side
Development 2 Web Server’s
Responsabilities
3 Quick Tour of PHP
4 Program Control
5 Functions
7
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Section 1 of 5
WHAT IS SERVER-SIDE
DEVELOPMENT
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
What is Server-Side
Development
The basic hosting of your files is achieved through a
web server.
Server-side development is much more than web
hosting: it involves the use of a programming
technology like PHP or ASP.NET to create scripts that
dynamically generate content
Consider distinction between client side and server
side…
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Comparing Client and Server
Scripts
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Server-Side Script Resources
So many tools in your kit
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Web Development Technologies
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Comparing Server-Side
Technologies
• ASP (Active Server Pages). Like PHP, ASP code (using the VBScript
programming language) can be embedded within the HTML. ASP
programming code is interpreted at run time, hence it can be slow
in comparison to other technologies.
• ASP.NET. ASP.NET is part of Microsoft’s .NET Framework and can
use any .NET programming language (though C# is the most
commonly used). ASP.NET uses an explicitly object-oriented
approach. It also uses special markup called web server controls
that encapsulate common web functionality such as database-
driven lists, form validation, and user registration wizards. ASP.NET
pages are compiled into an intermediary file format called MSIL
that is analogous to Java’s byte-code. ASP.NET then uses a Just-In-
Time compiler to compile the MSIL into machine executable code
so its performance can be excellent. However, ASP.NET is
essentially limited to Windows servers.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Comparing Server-Side
Technologies
• 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. Since JSP uses the Java Runtime Engine, it also
uses a JIT compiler for fast execution time and is cross-platform.
While JSP’s usage in the web as a whole is small, it has a
substantial market share in the intranet environment, as well as
with very large and busy sites.
• Node.js. This is a more recent server environment that uses
JavaScript on the server side, thus allowing developers already
familiar with JavaScript to use just a single language for both client-
side and server-side development. Unlike the other development
technologies listed here, node.js also is its own web server
software, thus eliminating the need for Apache, IIS, or some other
web server software.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Comparing Server-Side
Technologies
• Perl. Until the development and popularization of ASP, PHP, and
JSP, Perl was the language typically used for early server-side web
development. As a language, it excels in the manipulation of text. It
was commonly used in conjunction with the Common Gateway
Interface (CGI), an early standard API for communication between
applications and web server software.
• PHP. Like ASP, PHP is a dynamically typed language that can be
embedded directly within the HTML, though it now supports most
common object-oriented features, such as classes and inheritance.
By default, PHP pages are compiled into an intermediary
representation called opcodes that are analogous to Java’s byte-
code or the .NET Framework’s MSIL. Originally, PHP stood for
personal home pages, although it now is a recursive acronym that
means PHP: Hypertext Processor.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Comparing Server-Side
Technologies
• Python. This terse, object-oriented programming language
has many uses, including being used to create web
applications. It is also used in a variety of web development
frameworks such as Django and Pyramid.
• Ruby on Rails. This is a web development framework that
uses the Ruby programming language. Like ASP.NET and JSP,
Ruby on Rails emphasizes the use of common software
development approaches, in particular the MVC design
pattern. It integrates features such as templates and engines
that aim to reduce the amount of development work
required in the creation of a new site.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Market Share
Of web development environments
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Section 2 of 5
WEB SERVER’S
RESPONSABILITIES
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
A Web Server’s Responsibilities
A web server has many responsibilities:
• handling HTTP connections
• responding to requests for static and dynamic resources
• managing permissions and access for certain resources
• encrypting and compressing data
• managing multiple domains and URLs
• managing database connections
• managing cookies and state
• uploading and managing files
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
LAMP stack
WAMP, MAMP, …
You will be using the LAMP software stack
• Linux operating system
• Apache web server
• MySQL DBMS
• PHP scripting language
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Apache and Linux
LA
Consider the Apache web server as the intermediary
that interprets HTTP requests that arrive through a
network port and decides how to handle the request,
which often requires working in conjunction with PHP.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Apache
Continued
Apache runs as a daemon on the server. A daemon is
an executing instance of a program (also called a
process) that runs in the background, waiting for a
specific event that will activate it.
When a request arrives, Apache then uses modules to
determine how to respond to the request.
In Apache, a module is a compiled extension (usually
written in the C programming language) to Apache
that helps it handle requests. For this reason, these
modules are also sometimes referred to as handlers.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Apache and PHP
PHP Module in Apache
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Apache Threads
Multi-thread and multi-process
Apache runs in two possible modes:
• multi-process (also called preforked)
• multi-threaded (also called worker)
The default installation of Apache runs using the multi-
process mode.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Apache Threads
Multi-thread and multi-process
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PHP Internals
PHP itself is written in C
There are 3 main modules
1. PHP core. The Core module defines the main
features of the PHP environment, including
essential functions for variable handling, arrays,
strings, classes, math, and other core features.
2. Extension layer. This module defines functions for
interacting with services outside of PHP. This
includes libraries for MySQL, FTP, SOAP web
services, and XML processing, among others.
3. Zend Engine. This module handles the reading in
of a requested PHP file, compiling it, and executing
it.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Zend Engine
No, your code is not garbage.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Installing LAMP locally
Turn this key
The easiest and quickest way to do so is to use the
• EasyPHP for Windows only
• XAMPP For Windows installation package
• MAMP for Mac installation package
Both of these installation packages install and
configure Apache, PHP, and MySQL.
Later we can come back and configure these systems
in more detail.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
XAMPP Control Panel
Turn this key
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
XAMPP Settings
Defaults are
• PHP requests in your browser will need to use the
localhost domain (127.0.0.1)
• PHP files will have to be saved somewhere within
the C:\xampp\htdocs folder
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Section 3 of 5
QUICK TOUR OF PHP
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Quick Tour
• PHP, like JavaScript, is a dynamically typed
language.
• it uses classes and functions in a way consistent
with other object-oriented languages such as C++,
C#, and Java
• The syntax for loops, conditionals, and assignment
is identical to JavaScript
• Differs when you get to functions, classes, and in
how you define variables
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PHP Tags
The most important fact about PHP is that the
programming code can be embedded directly within
an HTML file.
• A PHP file will usually have the extension .php
• programming code must be contained within an
opening <?php tag and a matching closing ?> tag
• any code outside the tags is echoed directly out to
the client
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PHP Tags
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
HTML and PHP
Two approaches
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
HTML and PHP
Two approaches
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PHP Comments
3 kinds
The types of comment styles in PHP are:
• Single-line comments. Lines that begin with a # are
comment lines and will not be executed.
• Multiline (block) comments. These comments
begin with a /* and encompass everything that is
encountered until a closing */ tag is found.
• End-of-line comments. Whenever // is
encountered in code, everything up to the end of
the line is considered a comment.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PHP Comments
3 kinds
<?php
# single-line comment
/*
This is a multiline comment.
They are a good way to document functions or
complicated blocks of code
*/
$artist = readDatabase(); // end-of-line comment
?>
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Variables
Variables in PHP are dynamically typed.
Variables are also loosely typed in that a variable can
be assigned different data types over time
To declare a variable you must preface the variable
name with the dollar ($) symbol.
$count = 42;
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Data Types
Data Type Description
Boolean A logical true or false value
Integer Whole numbers
Float Decimal numbers
String Letters
Array A collection of data of any type (covered in the next chapter)
Object Instances of classes
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Constants
A constant is somewhat similar to a variable, except a
constant’s value never changes . . . in other words it
stays constant.
• Typically defined near the top of a PHP file via the
define() function
• once it is defined, it can be referenced without
using the $ symbol
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Constants
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Writing to Output
Hello World
To output something that will be seen by the browser,
you can use the echo() function.
echo ("hello"); //long form
echo "hello"; //shortcut
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
String Concatenation
Easy
Strings can easily be appended together using the
concatenate operator, which is the period (.) symbol.
$username = "World";
echo "Hello". $username;
Will Output Hello World
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
String Concatenation
Example
$firstName = "Pablo";
$lastName = "Picasso";
/*
Example one:
The first four lines are equivalent. Notice that you can reference PHP variables within a string literal
defined with double quotes.
The resulting output for the first four lines is: <em>Pablo Picasso</em>
The last one displays: <em> $firstName $lastName </em>
*/
echo "<em>" . $firstName . " ". $lastName . "</em>";
echo '<em>' . $firstName . ' '. $lastName. '</em>';
echo '<em>' . $firstName . ' '. $lastName. "</em>";
echo "<em> $firstName $lastName </em>";
echo '<em> $firstName $lastName </em>'; Won’t Work!!
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
String Concatenation
Example
/*
Example two:
These two lines are also equivalent. Notice that you
can use either the single quote symbol or double quote
symbol for string literals.
*/
echo "<h1>";
echo '<h1>';
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
String Concatenation
Example
/*
Example three:
These two lines are also equivalent. In the second
example, the escape character (the backslash) is used
to embed a double quote within a string literal defined
within double quotes.
*/
echo '<img src="23.jpg" >';
echo "<img src=\"23.jpg\" >";
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
String escape Sequences
Sequence Description
\n Line feed
\t Horizontal tab
\\ Backslash
\$ Dollar sign
\" Double quote
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Complicated Concatenation
echo "<img src='23.jpg' alt='". $firstName . " ". $lastName . "' >";
echo "<img src='$id.jpg' alt='$firstName $lastName' >";
echo "<img src=\"$id.jpg\" alt=\"$firstName $lastName\" >";
echo '<img src="' . $id. '.jpg" alt="' . $firstName . ' ' . $lastName . '" >';
echo '<a href="artist.php?id=' .$id .'">' .$firstName .' ' . $lastName .'</a>';
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Complicated Concatenation
echo "<img src='23.jpg' alt='". $firstName . " ". $lastName . "' >";
echo "<img src='$id.jpg' alt='$firstName $lastName' >";
echo "<img src=\"$id.jpg\" alt=\"$firstName $lastName\" >";
echo '<img src="' . $id. '.jpg" alt="' . $firstName . ' ' . $lastName . '" >';
echo '<a href="artist.php?id=' .$id .'">' .$firstName .' ' . $lastName .'</a>';
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Illustrated Example
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PrintF
Good ol’ printf
As an alternative, you can use the printf() function.
• derived from the same-named function in the C
programming language
• includes variations to print to string and files (sprintf,
fprintf)
• takes at least one parameter, which is a string, and that
string optionally references parameters, which are then
integrated into the first string by placeholder
substitution
• Can also apply special formatting, for instance, specific
date/time formats or number of decimal places
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PrintF
Illustrated example
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PrintF
Type specifiers
Each placeholder requires the percent (%) symbol in
the first parameter string followed by a type specifier.
• b for binary
• d for signed integer
• f for float
• o for octal
• x for hexadecimal
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
PrintF
Precision
Precision allows for control over how many decimal
places are shown. Important for displaying calculated
numbers to the user in a “pretty” way.
Precision is achieved in the string with a period (.)
followed by a number specifying how many digits
should be displayed for floating-point numbers.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Section 4 of 5
PROGRAM CONTROL
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
If…else
The syntax for conditionals in PHP is almost identical
to that of JavaScript
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
If…else
Alternate syntax
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Switch…case
Nearly identical
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
While and Do..while
Identical to other languages
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
For
Identical to other languages
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Alternate syntax for Control
Structures
PHP has an alternative syntax for most of its control
structures. In this alternate syntax
• the colon (:) replaces the opening curly bracket,
• while the closing brace is replaced with endif;,
endwhile;, endfor;, endforeach;, or endswitch;
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Include Files
Organize your code
PHP does have one important facility that is generally
unlike other nonweb programming languages, namely
the ability to include or insert content from one file
into another.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Include Files
Organize your code
PHP provides four different statements for including
files, as shown below.
include "somefile.php";
include_once "somefile.php";
require "somefile.php";
require_once "somefile.php";
With include, a warning is displayed and then
execution continues. With require, an error is
displayed and execution stops.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Include Files
Scope
Include files are the equivalent of copying and pasting.
• Variables defined within an include file will have
the scope of the line on which the include occurs
• Any variables available at that line in the calling file
will be available within the called file
• If the include occurs inside a function, then all of
the code contained in the called file will behave as
though it had been defined inside that function
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Section 5 of 5
FUNCTIONS
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Functions
You mean we don’t write everything in main?
Just as with any language, writing code in the main
function (which in PHP is equivalent to coding in the
markup between <?php and ?> tags) is not a good
habit to get into.
A function in PHP contains a small bit of code that
accomplishes one thing. In PHP there are two types of
function: user-defined functions and built-in functions.
1. A user-defined function is one that you the
programmer define.
2. A built-in function is one of the functions that
come with the PHP environment
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Functions
syntax
While the example function in Listing 8.13 returns a value, there is
no requirement for this to be the case.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Functions
No return – no big deal.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Call a function
Now that you have defined a function, you are able to
use it whenever you want to. To 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, or echo that return
value directly, as shown below.
$output = getNiceTime();
echo getNiceTime();
If the function doesn’t return a value, you can just call
the function:
outputFooterMenu();
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Parameters
Parameters are the mechanism by which values are
passed into functions.
To define a function with parameters, you must decide
• how many parameters you want to pass in,
• and in what order they will be passed
• Each parameter must be named
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Parameters
Thus to call our function, you can now do it in two ways:
echo getNiceTime(1); // this will print seconds
echo getNiceTime(0); // will not print seconds
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Parameter Default Values
Now if you were to call the function with no values, the
$showSeconds parameter would take on the default value, which we
have set to 1, and return the string with seconds.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Pass Parameters by Value
By default, arguments passed to functions are passed
by value in PHP. This means that PHP passes a copy of
the variable so if the parameter is modified within the
function, it does not change the original.
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Pass Parameters by Reference
PHP also allows arguments to functions to be passed
by reference, which will allow a function to change the
contents of a passed variable.
The mechanism in PHP to specify that a parameter is
passed by reference is to add an ampersand (&)
symbol next to the parameter name in the function
declaration
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Value vs Reference
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Variable Scope in functions
All variables defined within a function (such as parameter
variables) have function scope, meaning that they are only
accessible within the function.
Any variables created outside of the function in the main
script are unavailable within a function.
$count= 56;
function testScope() {
echo $count; // outputs 0 or generates run-
time
//warning/error
}
testScope();
echo $count; // outputs 56
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Global variables
Sometimes unavoidable
Variables defined in the main script are said to have
global scope.
Unlike in other programming languages, a global
variable is not, by default, available within functions.
PHP does allow variables with global scope to be
accessed within a function using the global keyword
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
What You’ve Learned
1 Server-Side
Development 2 Web Server’s
Responsabilities
3 Quick Tour of PHP
4 Program Control
5 Functions
7
Randy Connolly and Ricardo Hoar Fundamentals of Web Development