Module 4
Module 4
MODULE 4
1.1 Arrays
An array is a data structure that allows the programmer to collect a number of related
elements together in a single variable.
Unlike most other programming languages, in PHP an array is actually an ordered map,
which associates each value in the array with a key.
This flexibility allows us to use arrays in PHP in a manner similar to other languages’
arrays, but we can also use them like other languages’ collection classes.
Array keys
o In most programming languages array keys are limited to integers, i.e., start at
0,and go up by 1.
o In PHP, keys must be either integers or strings and need not be sequential.
o This means we cannot use an array or object as a key (doing so will generate an
error).
o One should be especially careful about mixing the types of the keys for an array
since PHP performs cast operations on the keys that are not integers or strings.
Array values
o Unlike keys, are not restricted to integers and strings.
Page 1
Web Programming 18AI643
To define the contents of an array as strings for the days of the week as shown in Figure
1.1, we declare it with a comma-delimited list of values inside the ( )braces using either
of two following syntaxes:
In the above example, because no keys are explicitly defined for the array, the default key
values are 0, 1, 2, . . . , n.
Notice that we do not have to provide a size for the array: arrays are dynamically sized as
elements are added to them.
Elements within a PHP array are accessed in a manner similar to other programming
languages, that is, using the familiar square bracket notation.
The code example below echoes the value of our $days array for the key=1, which results in
output of Tue.
We could also define the array elements individually using the same square bracket
notation:
Page 2
Web Programming 18AI643
In PHP, we are also able to explicitly define the keys in addition to the values.
This allows us to use keys other than the classic 0, 1, 2, . . , n to define the indexes of an
array.
Figure 1.2: Assigning keys to values (left) and Array with strings as keys and integers as values (left)
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).
This is why we can also consider an array to be a dictionary or hash map.
These types of arrays in PHP are generally referred to as associative arrays.
Keys must be either integer or string values, but the values can be any type of PHP data
type, including other arrays. e
To access an element in an associative array, we simply use the key value rather than an
index.
Multidimensional Arrays
PHP also supports multidimensional arrays.
The values for an array can be any PHP object, which includes other arrays.
Page 3
Web Programming 18AI643
Listing 1.1 illustrates how to iterate and output the content of the $days array using the
built-in function count() along with examples using while, do while, and for loops.
Listing 1.1: Iterating an array using while, Listing 1.2: Iterating through an associative array
do while, and for loops using a foreach loop
The challenge of using the classic loop structures is that when we have nonsequential
integer keys (i.e., an associative array), we can’t write a simple loop that uses the $i++
construct.
To overcome this challenge we need to use iterator to move through an associative array
as shown in Listing 1.2.
Adding and Deleting Elements
In PHP, arrays are dynamic, i.e., they can grow or shrink in size.
An element can be added to an array simply by using a key/index that hasn’t been used,
as shown below:
Since there is no current value for key 5, the array grows by one, with the new key/value
pair added to the end of our array.
If the key had a value already, the same style of assignment replaces the value at that key.
Page 4
Web Programming 18AI643
As an alternative to specifying the index, a new element can be added to the end of any
array using the following technique:
The advantage to this approach is that we don’t have to worry about skipping an index
key. PHP is more than happy to let us “skip” an index, as shown in the following
example.
o That is, there is now a “gap” in our array that will cause problems if we try
iterating through it using the techniques.
o If we try referencing $days[6], for instance, it will return a NULL value, which is
a special PHP value that represents a variable with no value.
We can also create “gaps” by explicitly deleting array elements using the unset() function
as shown in Listing 1.3.
Listing 1.3: Deleting elements Listing 1.4: nonsequential keys and usage of isset( )
Page 5
Web Programming 18AI643
Array Sorting
There are many built-in sort functions, which sort by key or by value. To sort the $days
array by its values we would simply use:
o As the values are all strings, the resulting array would be:
However, the above sort loses the association between the values and the keys!
A better sort, one that would have kept keys and values associated together, is:
array_keys($someArray): This method returns an indexed array with the values being
the keys of $someArray.
o For example, print_r(array_values($days)) outputs
Page 6
Web Programming 18AI643
in_array($needle, $haystack): This method lets us to search array $haystack for a value
($needle). It returns true if it is found, and false otherwise.
shuffle($someArray): This method shuffles $someArray. Any existing keys are removed
and $someArray is now an indexed array if it wasn’t already.
Superglobal Arrays
PHP uses special predefined associative arrays called superglobal variables that allow the
programmer to easily access HTTP headers, query string parameters, and other
commonly needed information.
They are called superglobal because these arrays are always in scope and always exist,
ready for the programmer to access or modify them without having to use the global
keyword.
Page 7
Web Programming 18AI643
Figure1.5: HTTP request to $_GET array Figure1.6: HTTP request to $_POST array
If the form was sent using HTTP POST, then the values would not be visible in the URL,
but will be sent through HTTP POST request body.
From the PHP programmer’s perspective, almost nothing changes from a GET data post
except that those values and keys are now stored in the $_POST array.
This mechanism greatly simplifies accessing the data posted by the user, since we need
not parse the query string or the POST request headers.
Determining If Any Data Sent
PHP can use the same file to handle both the display of a form as well as the form
input.
o For example, a single file is often used to display a login form to the user, and
that same file also handles the processing of the submitted form data, as
shown in Figure 1.7.
o In such cases we may want to know whether any form data was submitted at
all using either POST or GET.
Page 8
Web Programming 18AI643
Figure 1.7: Form display and processing by the same PHP page
Listing 1.5: HTML that enables multiple Listing 1.6: PHP code to display an array
values for one name of checkbox variables
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[].
Listing 1.6 to echo the number of days selected and their values.
Page 9
Web Programming 18AI643
Figure 1.8: Sensible approach to displaying individual items using query strings
Our program must be able to handle the following cases for every query string or
form value.
o If query string parameter doesn’t exist.
o If query string parameter doesn’t contain a value.
Page 10
Web Programming 18AI643
Figure 1.9: Relationship between request headers, the server, and the $_SERVER array
To use the $_SERVER array, we simply refer to the relevant case-sensitive key name:
It is worth noting that because the entries in this array are created by the webserver, not
every key listed in the PHP documentation will necessarily be available.
A complete list of keys contained within this array is listed in the online PHP
documentation, but we will cover some of the critical ones here.
Page 11
Web Programming 18AI643
DOCUMENT_ROOT tells us the file location from which we are currently running
our script.
Since we are often moving code from development to production, this key can be
used to great effect to create scripts that do not rely on a particular location to run
correctly.
This key complements the SCRIPT_NAME key that identifies the actual script being
executed.
Listing 1.8: Accessing the user-agent string Listing 1.9: Using the HTTP_REFERER header
in the HTTP headers to provide context-dependent output
One of the most commonly used request headers is the user-agent header, which
contains the operating system and browser that the client is using. This header value
can be accessed using the key HTTP_USER_AGENT as shown in Listing 1.8.
HTTP_REFERER is an especially useful header. Its value contains the address of the
page that referred us to this one (if any) through a link. It is commonly used in
analytics to determine which pages are linking to our site as shown in Listing 1.9.
Page 12
Web Programming 18AI643
Figure 1.10: Data flow from HTML form through POST to PHP $_FILES array
Page 13
Web Programming 18AI643
Figure 1.10 illustrates the process of uploading a file to the server and how the
corresponding upload information is contained in the $_FILES array.
The values for each of the keys, in general, are described below.
o Name is a string containing the full file name used on the client machine,
including any file extension. It does not include the file path on the client’s
machine.
o Type defines the MIME type of the file. This value is provided by the client
browser and is therefore not a reliable field.
o tmp_name is the full path to the location on your server where the file is being
temporarily stored. The file will cease to exist upon termination of the script, so it
should be copied to another location if storage is required.
o error is an integer that encodes many possible errors and is set to
UPLOAD_ERR_OK (integer value 0) if the file was uploaded successfully.
o size is an integer representing the size in bytes of the uploaded file.
Table 1.2: Error Codes in PHP for Listing 1.11: Checking each file
File Upload uploaded for errors
Page 14
Web Programming 18AI643
A proper file upload script will therefore check each uploaded file by checking the
various error codes as shown in listing 1.11.
File Size Restrictions
Some scripts limit the file size of each upload.
There are many reasons to do so, and ideally we would prevent the file from even being
transmitted in the first place if it is too large.
There are three main mechanisms for maintaining uploaded file size restrictions:
o via HTML in the input form,
o This technique allows your php.ini maximum file size to be large,
while letting some forms override that large limit with a smaller one
Page 15
Web Programming 18AI643
Even if the upload was successful and the size was within the appropriate limits, we may
still have a problem.
What if we wanted the user to upload an image and they uploaded a Microsoft Word
document? We might also want to limit the uploaded image to certain image types, such
as jpg and png, while disallowing bmp and others.
To accomplish this type of checking you typically examine the file extension and the type
field and also to compare the type to valid image types.
Listing 1.15 shows sample code to check the file extension of a file, and also to compare
the type to valid image types.
Listing 1.15: PHP code to look for valid Listing 1.16: Using move_uploaded_file() function
mime types and file extensions
Page 16
Web Programming 18AI643
Even if our site uses a database for storing its information, the fact that the PHP file
functions can read/write from a file or from an external website (i.e., from a URL) means
that file system functions still have relevance even in the age of database-driven websites.
There are two basic techniques for read/writing files in PHP:
o Stream access. In this technique, our code will read just a small portion of the file
at a time. While this does require more careful programming, it is the most
memory-efficient approach when reading very large files.
o All-In-Memory access. In this technique, we can read the entire file into memory
(i.e., into a PHP variable). While not appropriate for large files, it does make
processing of the file extremely easy.
Stream access
In the C-style file access you separate the acts of opening, reading, and closing a file.
The function fopen() takes a file location or URL and access mode as parameters.
Some of the common modes are “r” for read, “rw” for read and write, and “c,” which
creates a new file for writing.
Once the file is opened, we can read from it in several ways.
o To read a single line, use the fgets() function, which will return false if there is
no more data,
o To read an arbitrary amount of data (typically for binary files), use fread() and
for reading a single character use fgetsc().
o Finally, when finished processing the file you must close it using fclose().
Listing 1.17 illustrates a script using fopen(), fgets(), and fclose() to read a file and
echo it out.
To write data to a file, we can employ the fwrite() function in much the same way as
fgets(), passing the file handle and the string to write.
Listing 9.19 Opening, reading lines, Table 1.3: In-Memory File Functions
and closing a file
Page 17
Web Programming 18AI643
All-In-Memory access
While the previous approach to reading/writing files gives you complete control, the
programming requires more care in dealing with the streams, file handles, and other
low-level issues.
The alternative simpler approach is much easier to use, at the cost of relinquishing
fine-grained control as shown in table 1.3.
The file_get_contents() and file_put_contents() functions allow you to read or write
an entire file in one function call. To read an entire file into a variable you can
simply use:
These functions are especially convenient when used in conjunction with PHP’s
many powerful string-processing functions.
1. Object-Oriented Overview
2. Classes and Objects in PHP
3. Object Oriented Design
The notion of programming with objects allows the developer to think about an item
with particular properties (attributes /data members) and methods (functions).
The structure of these objects are defined by classes, which outline the 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, and behaves independently from the class once
created.
Page 18
Web Programming 18AI643
Figure 2.1 illustrates the differences between a class, which defines an object’s
properties and methods, and the objects or instances of that class.
Figure 2.2: Relationship between a class Figure 2.3: Different levels of UML detail
and its objects in UML
Page 19
Web Programming 18AI643
One important distinction between web programming and desktop application programming
is that the objects you create (normally) only exist until a web script is terminated.
While desktop software can load an object into memory and make use of it for several user
interactions, a PHP object is loaded into memory only for the life of that HTTP request.
Figure 10.4 shows an illustration of the lifetimes of objects in memory between a desktop and
a browser application.
For this reason, we must use classes differently than in the desktop world, since the object
must be recreated and loaded into memory for each request that requires it.
Object-oriented web applications can see significant performance degradation compared to
their functional counterparts if objects are not utilized correctly.
Unlike a desktop, there are potentially many thousands of users making requests at once, so
not only objects are destroyed upon responding to each request, but memory must be shared
between many simultaneous requests, each of which may load objects into memory.
Page 20
Web Programming 18AI643
Defining Classes
The PHP syntax for defining a class uses the class keyword followed by the
classname and { } braces.
The properties and methods of the class are defined within the braces.
The Artist class with the properties illustrated in Figure 2.2 is defined using PHP
in Listing 2.1.
Each property in the class is declared using one of the keywords public, protected,
or private followed by the property or variable name.
Listing 2.1: Artist class Listing 2.2 Instantiating two Artist objects and setting its object’s properties
Instantiating Objects
It’s important to note that defining a class is not the same as using it.
To make use of a class, one must instantiate (create) objects from its definition
using the new keyword.
To create two new instances of the Artist class called $picasso and $dali, we
instantiate two new objects using the new keyword as follows:
Properties
Once we have instances of an object, we can access and modify the properties of
each one separately using the variable name and an arrow (), which is
constructed from the dash and greater than symbols.
Listing 2.2 Shows code that defines the two Artist objects and then sets all the
properties for the $picasso object.
Constructors
Listing 2.2 takes multiple lines and every line of code introduces potential
maintainability problems, especially when we define more artists.
Inside of a class definition, we should therefore define constructors.
In PHP, constructors are defined as functions with the name construct().
Page 21
Web Programming 18AI643
Listing 2.3 shows an updated Artist class definition that now includes a
constructor.
Inside of a class you must always use the $this syntax to reference all properties
and methods associated with this particular instance of a class.
Listing 2.3: A constructor added to the class definition Listing 2.4: Method definition
This new constructor can then be used when instantiating as shown below
Methods
Objects are useful when we define behavior or operations that they can perform.
In object-oriented lingo these operations are called methods and are like
functions, except they are associated with a class as shown in listing 2.4.
They define the tasks each instance of a class can perform and are useful since
they associate behavior with objects.
To output the artist, you can use the reference and method name as follows:
Page 22
Web Programming 18AI643
Visibility
The visibility of a property or method determines the accessibility of a class
member (i.e., a property or method) and can be set to public, private, or protected.
Static Members
A static member is a property or method that all instances of a class share and
there is only one value for a class’s static property.
To illustrate how a static member is shared between instances of a class, we will
add the static property artistCount to our Artist class, and use it to keep a count of
how many Artist objects are currently instantiated.
Page 23
Web Programming 18AI643
This variable is declared static by including the static keyword in the declaration
as shown in listing 2.5
Class Constants
To add a property to a class that is constant as same as static members but with a
const keyword.
However, constant values can be stored more efficiently as class constants so long
as they are not calculated or updated.
Page 24
Web Programming 18AI643
Unlike all other variables, constants don’t use the $ symbol when declaring or
using them.
They can be accessed both inside and outside the class using
self::EARLIEST_DATE in the class and classReference::EARLIEST_DATE
outside.
Data Encapsulation
The most important advantage to object-oriented design is the possibility of
encapsulation, which generally refers to restricting access to an object’s internal
components.
Another way of understanding encapsulation is: it is the hiding of an object’s
implementation details.
A properly encapsulated class will define an interface to the world in the form of its
public methods, and leave its data, that is, its properties, hidden (that is, private).
If a properly encapsulated class makes its properties private, then the typical approach
is to write methods for accessing and modifying properties rather than allowing them
to be accessed directly.
These methods are commonly called getters and setters (or accessors and mutators).
A getter to return a variable’s value is often very straightforward and should not
modify the property.
It is normally called without parameters, and returns the property from within the
class.
Setter methods modify properties, and allow extra logic to be added to prevent
properties from being set to strange values.
Page 25
Web Programming 18AI643
Ex:
Page 26
Web Programming 18AI643
Just as in Java, a PHP class is defined as a subclass by using the extends keyword.
Inheriting Methods
o Every method defined in the base/parent class can be overridden when extending
a class, by declaring a function with the same name.
o To access a public or protected method or property defined within a base class
from within a subclass, we do so by prefixing the member name with parent::. So
to access the parent’s toString() method we would simply use
parent:: toString().
Parent Constructors
o If we want to invoke a parent constructor in the derived class’s constructor, we
can use the parent:: syntax and call the constructor on the first line parent::
construct().
o This is similar to calling other parent methods, except that to use it we must call
it at the beginning of our constructor.
Polymorphism
Polymorphism is the third key object-oriented concept (along with encapsulation and
inheritance).
Polymorphism is the notion that an object can in fact be multiple things at the same
time.
Let us begin with an instance of a Painting object named $guernica created as follows:
Page 27
Web Programming 18AI643
The variable $guernica is both a Painting object and an Art object due to its
inheritance.
The advantage of polymorphism is that we can manage a list of Art objects, and call
the same overridden method on each.
Object Interfaces
An object interface is a way of defining a formal list of methods that a class must
implement without specifying their implementation.
Interfaces provide a mechanism for defining what a class can do without specifying
how it does it, which is often a very useful design technique.
Interfaces are defined using the interface keyword, and look similar to standard PHP
classes, except an interface contains no properties and its methods do not have method
bodies defined.
Ex:
An interface contains only public methods, and instead of having a method body, each
method is terminated with a semicolon.
In PHP, a class can be said to implement an interface, using the implements keyword.
This means then that the class Painting must provide implementations (i.e., normal
method bodies) for the getSize() and getPNG() methods.
Page 28
Web Programming 18AI643
Types of Errors
Not every problem is unexpected or catastrophic. One might say that there are three
different types of website problems:
■ Expected errors
■ Warnings
■ Fatal errors
An expected error is an error that routinely occurs during an application. Perhaps the
most common example of this type would be an error as a result of user inputs, for
instance, entering letters when numbers were expected.
Another type of error is warnings, which are problems that generate a PHP warning
message (which may or may not be displayed) but will not halt the execution of the
page. For instance, calling a function without a required parameter will generate a
warning message but not stop execution.
The final type of error is fatal errors, which are serious in that the execution of the page
will terminate unless handled in some way. These should truly be exceptional and
unexpected, such as a required input file being missing or a database table or field
disappearing.
Page 29
Web Programming 18AI643
Exceptions
Developers sometimes treat the words “error” and “exception” as synonyms. In the
context of PHP, they do have different meanings.
An error is some type of problem that generates a nonfatal warning message or that
generates an error message that terminates the program’s execution.
An exception refers to objects that are of type Exception and which are used in
conjunction with the object-oriented try . . . catch language construct for dealing with
runtime errors.
o The possible levels for error_reporting are defined by predefined constants lists
some of the most common values. It is worth noting that in some PHP
environments, the default setting is zero, that is, no reporting.
Page 30
Web Programming 18AI643
o The display_error setting specifies whether error messages should or should not
bedisplayed in the browser.2 It can be set programmatically via the ini_set()
function:
o The log_error setting specifies whether error messages should or should not be sent to
the server error log. It can be set programmatically via the ini_set() function:
In the procedural approach to error handling, the programmer needs to explicitly test for
error conditions after performing a task that might generate an error.
In such a case we needed to test for and deal with errors after each operation that might
generate an error state.
While this approach might seem more straightforward, it does require the programmer to
know ahead of time what code is going to generate an error condition.
The advantage of the try . . . catch mechanism is that it allows the developer to handle a
wider variety of exceptions in a single catch block.
Even with explicit testing for error conditions, there will still be situations when an
unforeseen error occurs. In such a case, unless a custom error handler has been defined,
PHP will terminate the execution of the application.
Page 31
Web Programming 18AI643
Page 32
Web Programming 18AI643
It is possible to define our own handler for uncaught errors and exceptions; the
mechanism for doing so varies depending upon whether you are using the procedural or
object-oriented mechanism for responding to errors.
If using the procedural approach (i.e., not using try . . . catch), we can define a custom
error-handling function and then register it with the set_error_handler() function.
If we are using the object-oriented exception approach with try . . . catch blocks, we can
define a custom exception-handling function and then register it with the
set_exception_handler() function.
Page 33