PHP 8 Basics
PHP 8 Basics
PHP 8 Basics
Gunnard Engebreth
Satej Kumar Sahu
PHP 8 Basics: For Programming and Web Development
Gunnard Engebreth Satej Kumar Sahu
Madison, WI, USA Bangalore, India
Acknowledgments�����������������������������������������������������������������������������xix
Introduction���������������������������������������������������������������������������������������xxi
v
Table of Contents
vi
Table of Contents
strtoupper( )���������������������������������������������������������������������������������������������������66
is_string( )������������������������������������������������������������������������������������������������������66
strstr( )�����������������������������������������������������������������������������������������������������������67
PHP Data Types: Compound Types����������������������������������������������������������������������68
Array�������������������������������������������������������������������������������������������������������������������68
Object������������������������������������������������������������������������������������������������������������������71
PHP Data Types: Special Types����������������������������������������������������������������������������71
NULL��������������������������������������������������������������������������������������������������������������������71
resource��������������������������������������������������������������������������������������������������������������72
Summary������������������������������������������������������������������������������������������������������������72
Chapter 6: Arrays��������������������������������������������������������������������������������85
PHP Indexed and Associative Arrays�������������������������������������������������������������������85
PHP Multidimensional Arrays������������������������������������������������������������������������������91
PHP Array Functions��������������������������������������������������������������������������������������������91
array_change_key_case�������������������������������������������������������������������������������93
array_chunk��������������������������������������������������������������������������������������������������93
array_column������������������������������������������������������������������������������������������������94
array_combine����������������������������������������������������������������������������������������������95
array_count_values���������������������������������������������������������������������������������������95
array_diff_assoc��������������������������������������������������������������������������������������������96
array_diff_key�����������������������������������������������������������������������������������������������96
array_diff_uassoc�����������������������������������������������������������������������������������������97
array_diff_ukey���������������������������������������������������������������������������������������������97
vii
Table of Contents
array_diff�������������������������������������������������������������������������������������������������������98
array_fill_keys�����������������������������������������������������������������������������������������������99
array_fill��������������������������������������������������������������������������������������������������������99
array_filter���������������������������������������������������������������������������������������������������100
array_flip�����������������������������������������������������������������������������������������������������101
array_intersect_assoc���������������������������������������������������������������������������������101
array_intersect_key������������������������������������������������������������������������������������102
array_intersect_uassoc�������������������������������������������������������������������������������102
array_intersect_ukey����������������������������������������������������������������������������������103
array_intersect��������������������������������������������������������������������������������������������104
array_is_list�������������������������������������������������������������������������������������������������104
array_key_exists�����������������������������������������������������������������������������������������105
array_key_first��������������������������������������������������������������������������������������������105
array_key_last���������������������������������������������������������������������������������������������106
array_keys���������������������������������������������������������������������������������������������������106
array_map���������������������������������������������������������������������������������������������������107
array_merge_recursive�������������������������������������������������������������������������������108
array_merge������������������������������������������������������������������������������������������������108
array_multisort��������������������������������������������������������������������������������������������109
array_pad����������������������������������������������������������������������������������������������������110
array_pop����������������������������������������������������������������������������������������������������110
array_product����������������������������������������������������������������������������������������������111
array_push��������������������������������������������������������������������������������������������������111
array_rand���������������������������������������������������������������������������������������������������112
array_reduce�����������������������������������������������������������������������������������������������113
array_replace_recursive�����������������������������������������������������������������������������113
array_replace����������������������������������������������������������������������������������������������114
array_reverse����������������������������������������������������������������������������������������������115
viii
Table of Contents
array_search�����������������������������������������������������������������������������������������������115
array_shift���������������������������������������������������������������������������������������������������116
array_slice���������������������������������������������������������������������������������������������������117
array_splice�������������������������������������������������������������������������������������������������118
array_sum���������������������������������������������������������������������������������������������������120
array_udiff_assoc���������������������������������������������������������������������������������������120
array_udiff_uassoc�������������������������������������������������������������������������������������121
array_udiff���������������������������������������������������������������������������������������������������122
array_uintersect_assoc�������������������������������������������������������������������������������123
array_uintersect_uassoc�����������������������������������������������������������������������������123
array_uintersect������������������������������������������������������������������������������������������124
array_unique�����������������������������������������������������������������������������������������������125
array_unshift�����������������������������������������������������������������������������������������������126
array_values������������������������������������������������������������������������������������������������126
array_walk_recursive����������������������������������������������������������������������������������127
array_walk���������������������������������������������������������������������������������������������������127
array������������������������������������������������������������������������������������������������������������128
arsort�����������������������������������������������������������������������������������������������������������129
assort�����������������������������������������������������������������������������������������������������������130
compact�������������������������������������������������������������������������������������������������������131
count�����������������������������������������������������������������������������������������������������������131
current���������������������������������������������������������������������������������������������������������132
each�������������������������������������������������������������������������������������������������������������133
end��������������������������������������������������������������������������������������������������������������134
extract���������������������������������������������������������������������������������������������������������134
in_array�������������������������������������������������������������������������������������������������������136
key_exists���������������������������������������������������������������������������������������������������137
key���������������������������������������������������������������������������������������������������������������137
ix
Table of Contents
krsort�����������������������������������������������������������������������������������������������������������137
ksort������������������������������������������������������������������������������������������������������������138
list����������������������������������������������������������������������������������������������������������������139
natcasesort��������������������������������������������������������������������������������������������������139
natsort���������������������������������������������������������������������������������������������������������140
next��������������������������������������������������������������������������������������������������������������140
prev�������������������������������������������������������������������������������������������������������������141
range�����������������������������������������������������������������������������������������������������������142
reset������������������������������������������������������������������������������������������������������������142
rsort�������������������������������������������������������������������������������������������������������������143
shuffle���������������������������������������������������������������������������������������������������������144
sizeof�����������������������������������������������������������������������������������������������������������144
sort��������������������������������������������������������������������������������������������������������������144
uasort����������������������������������������������������������������������������������������������������������145
uksort����������������������������������������������������������������������������������������������������������146
usort������������������������������������������������������������������������������������������������������������146
Summary����������������������������������������������������������������������������������������������������������147
Chapter 8: Objects����������������������������������������������������������������������������165
Output���������������������������������������������������������������������������������������������������������������167
Summary����������������������������������������������������������������������������������������������������������169
x
Table of Contents
xi
Table of Contents
xii
Table of Contents
Index�������������������������������������������������������������������������������������������������315
xiii
About the Authors
Gunnard Engebreth began coding at the age
of 11 through a “Learning BASIC” book given
to him by his father. Technology was changing
fast, and Gunnard rode the wave from 1200 to
56k baud modems. Logging into BBSs, Prodigy,
CompuServe, Delphi, and IRC, he could see
the world changing and he wanted to be a part
of it. He soon got involved in the ANSI/demo
scene, making several application generators
for many groups in the 1990s. Visual Basic was
his next language of choice, allowing him to develop “tools” for online
systems such as AOL. This introduced many aspects of development,
security, and user interfaces while they were still in their infancy. Once
the World Wide Web arrived via Mindspring in Atlanta, Georgia, Gunnard
quickly joined in the race for the Web. Learning HTML, PERL, and Linux
(Slackware at the time), he began to build his skill set, which led to a
full-time systems administrator position at the age of 20 (2000) at
Activegrams/Silverpop. Gunnard has moved around the IT industry
from SAN/NAS storage at IBM to custom WordPress sites for marketing
companies, but one thing has stayed the same: his passion for learning
and problem solving. Gunnard also DJs drum and bass as Section31, plays
drums, and bakes bread (www.gunnard.org).
xv
About the Authors
xvi
About the Contributor
Massimo Nardone has more than 26 years
of experience in security, web/mobile
development, and cloud and IT architecture.
His true IT passions are security and Android.
He has been programming and teaching how
to program with Android, Perl, PHP, Java, VB,
Python, C/C++, and MySQL for more than 25
years. He holds a Master of Science degree
in Computing Science from the University
of Salerno, Italy. He has worked as a Chief
Information Security Office (CISO), software
engineer, chief security architect, security executive, OT/IoT/IIoT Security
Leader, and architect for many years.
xvii
Acknowledgments
I would like to dedicate this book to my parents for always believing in
and having patience with me while I pursued my interest in technology,
and gave me the freedom to explore and try different things. Also, thanks
to my sister Lipsa for always being beside me whenever I needed her. I
would like to thank all my teachers for being with me during my journey,
Runish for the foundational mentoring support at the start of my career,
Mindfire Solutions for my first career opportunity, and to all with whom I
had an opportunity to interact and learn from. Last but not least I would
like to thank Mark for the awesome opportunity to write my first book and
the wonderful team at Apress for all their support without whom this book
would not have been possible.
xix
Introduction
Developing web pages and applications is still, after many years, one of the
most fascinating endeavors for developers. The idea of taking a simple idea
and developing it, seeing it coming alive and imagining the experience the
user will have is something very magical.
The experience of programming as web developer should, of course,
also be easy, user-friendly, and flexible—all characteristics of the
programming language this book is all about: PHP version 8.
The first version of PHP was created by Rasmus Lerdorf in 1994 and
he mainly used it on his home page to keep track of who was looking at
his online resume. In 1995, the first public version was published as the
Personal Home Page Tools.
In the beginning, PHP was just a simple programming language with
a very easy parser engine that only understood a small number of utilities
and macros.
PHP usage grown. In 1996, about 15,000 web sites were developed with
PHP; by 1997, it was up to 50,000. In 1999, about 1 million web sites were
developed with PHP. At the time of writing, 78 million of web sites have
been developed with PHP to give you a perspective of how popular this
programming language has become. Why?
Simple. Because after many years it is still easy to use, user-friendly,
and clearly organized. This helps would-be programmers easily
understand and run PHP commands and functions.
We want to help PHP beginners and would-be developers explore
the new features added to this version 8 and see how easy, flexible, and
powerful it can be to develop new web sites and applications.
xxi
Introduction
You will find all the basic information about how to install and
configure PHP version 8.
All basic PHP concepts like data types, functions, regular expressions,
form handling and verification, sessions, cookies, and filters are
introduced and demonstrated with many examples.
We also introduce the basic information of object-oriented
programming and its classes and objects.
This book also provides some simple examples about how to use
PHP version 8 with one of the most powerful and used databases for
developers, MySQL. You learn how to develop an entire web application
using PHP version 8 and MySQL.
You also learn about PHP frameworks and why they are so important
to use. This book focuses on just two of the many PHP frameworks
available, Symfony and Laravel, and the development of web applications
following the model–view–controller architectural pattern.
Prerequisites
The examples in this book were built with PHP version 8. We also used
MySQL for Ubuntu Linux version 22.04 DEB Bundle. As a testing tool,
we used the latest Postman API client version available on the Web, but
you are free to use any testing tool you feel comfortable with. Finally, we
xxii
Introduction
introduced and utilized two different PHP Frameworks named Laravel and
Symfony, which will be needed for the examples of this book.
Downloading the Code
The source code for the examples in this book is available at www.github.
com/apress/php8-basics.
xxiii
CHAPTER 1
Getting Started
PHP is the de facto programming language used to serve billions (“BILL”
not “MILL”) a month. PHP has grown from a hodge-podge collection of
scripts that could be used to stitch together a functional website into the
backbone of several billion-dollar companies influencing how industry
works across the globe. Yes, there are other languages out there that do
many things, but you are not reading this book to understand them! You
chose to step into the world of PHP and join the network of developers
who focus on solutions, community, and the advancement of PHP. This
chapter of the book will cover the why, when, and how of using the
PHP programming language. It will also introduce some programming
development environments and describe how to install Docker, which is
an open platform for developing, shipping, and running applications.
Any one of those sites above pull impressive numbers, but when
combined, they are pretty hefty statistics. Even if you have a loyalty to
another programming language, you can’t deny the use of PHP as a
workhorse in these sites. While we can see that large corporations have
come to trust the language, what about average users like you and me?
Over 39.5% of all websites on the Internet are run on WordPress. Let that
sink in for a minute. Almost 40% of all websites are served up on a CMS
(open source, no less) that is developed in PHP.
PHP is exploding yearly in terms of demand. A quick check on any job
search website will give you thousands of results.
PHP is continuously growing, with scheduled releases and a thriving
community of developers maintaining technological relevance.
PHP is the most exciting AND the most practical programming
language you can get started with today.
Admittedly, we may have our biases.
Using PHP
PHP is mainly used by developers in two ways. One method is to organize
and deliver data from a data source (i.e., a MySQL database) to a webpage.
Think of Facebook or Twitter. The content that you see on these sites is
stored somewhere in a database and needs to be retrieved and then parsed
or organized, ultimately leading to a front-end display to the user. Your
cousin’s baby pictures with 40 likes must be gathered, the likes must be
collected and names attributed to them, and then they are ready to pop up
on your timeline. Depending on the infrastructure, this data can be stored
in one location or multiple places, tied together with unique identifiers.
We may be getting ahead of ourselves here, but we are trying to convey the
fact that the information you see on webpages is cultivated by PHP from
information stored in databases. PHP is the toolbox you will use to build
these powerful applications.
2
Chapter 1 Getting Started
We mentioned that there are two main ways to use PHP. The other
way is on the command line. There are usually several scripting languages
on a server that can be used to perform all sorts of tasks. Bash, Python,
and Perl come to mind, but PHP can be used in the same way. If you have
not already, go to the GitHub repo linked from this book’s apress.com
product page and look at the Chapter 1 link. From here, you will set up the
development environment in order to look at and run these PHP scripts.
Let’s get the development environment spun up so you can see PHP
in action.
PHP is a server-side scripting language and therefore needs a server
with the appropriate settings and resources to run. While PHP comes
natively installed on many operating systems, it can be installed or
upgraded on its own. Examples of other server-side languages are Python,
Ruby, and Perl. The opposite of this is client-side languages. They are
processed in the browser and are based on JavaScript. Examples of client-
side languages are Vue.js, jQuery, and Node.js.
3
Chapter 1 Getting Started
to protect directories from being viewed across the Web. For example, if
you have an assets/ directory with private information that is publicly
accessible, say gunnard.org/assets, but there is no index.html, this will
be viewable to anyone, and they will see a list of files in that directory. If
a blank index.html is placed there, the file will be shown instead. Within
Nginx you can set the priority and order in which Nginx looks for these
default files. When using PHP, it is necessary to specify that Nginx looks for
index.php over index.html, for example.
In order to use your development environment, you need a tool called
Docker. Docker provides your computer (the host machine) with the
ability to masquerade as a web server, in your example, without creating a
virtual machine separate from your host environment. This might sound
like the exact thing you WANT to do, which it is, but Docker goes about it
in a slightly different way that is more robust, easier to manage, and less
invasive than your typical virtual machine. Think of Docker as software
that allows for a container to dress up like a specific type of computer
or server. This container is separate from your host system but also uses
the resources (directories, CPU, memory) of your host without actually
changing or creating a new machine. The inner workings of Docker vs.
virtual machines is outside of the scope of this book and frankly could
take an entire book to explain it much better than we just did. The bottom
line is that with Docker, we control and can use the beneficial parts of a
web server without having to create, install, and maintain a real or virtual
server. Plus, as of printing, this is what 99% of development shops use; this
is very industry standard.
Installing Docker
Let’s get Docker installed on your operating system of choice. Here’s how
to do it.
4
Chapter 1 Getting Started
Windows
Go to https://docs.docker.com/docker-for-windows/install/ and
click the “Docker Desktop for Windows” button to download Docker, as
shown in Figure 1-1.
5
Chapter 1 Getting Started
Mac OS
Go to https://docs.docker.com/docker-for-mac/install/, shown in
Figure 1-2.
6
Chapter 1 Getting Started
The Docker menu in the top status bar indicates that Docker Desktop
is running and accessible from a terminal.
Linux
Go to https://docs.docker.com/engine/install/. Here you will find
links to instructions on how to install Docker on several popular Linux
7
Chapter 1 Getting Started
<code>
sudo apt-get remove docker docker-engine docker.io
containerd runc
</code>
<code>
sudo apt-get update
sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg \
lsb-release
</code>
<code>
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo
gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
</code>
8
Chapter 1 Getting Started
<code>
echo \
"deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-
keyring.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.
list.d/docker.list > /dev/null
</code>
<code>
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
</code>
9
Chapter 1 Getting Started
Installing Docker-Compose
Mac and Windows users that have installed Docker Desktop can skip the
installation step because Compose is included with the installed package.
<code>
sudo curl -L "https://github.com/docker/compose/releases/
download/1.29.1/docker-compose-$(uname -s)-$(uname -m)" -o /
usr/local/bin/docker-compose
</code>
<code>
sudo chmod +x /usr/local/bin/docker-compose
</code>
10
Chapter 1 Getting Started
For example,
<code>
sudo ln -s /usr/local/bin/docker-compose /usr/bin/
docker-compose
</code>
Optionally, install command completion for the bash and zsh shells.
Test the installation.
<code>
$ docker-compose --version
</code>
11
Chapter 1 Getting Started
Once you have the ZIP file downloaded, unzip it in a directory of your
choosing. We used ~/ (my users home directory) ~/coding. Once
unzipped, your directory structure should look something like Figure 1-6.
Inside this directory will be all the information needed for Docker to
start the development environment.
Go ahead and run
<code>
docker-compose up
</code>
<code>
http://localhost:8000
</code>
12
Chapter 1 Getting Started
and you should see the table of contents page for this book and
verification that the database has connected successfully. Go to the
command prompt and type
<code>
docker ps
</code>
<code>
docker exe -ti php-app bash
</code>
This connects you, much like ssh, to the container itself. From here, go
into the Chapter1 directory.
<code>
cd Chapter1
</code>
Type
<code>
php first_script.php
</code>
<code>
Output here
</code>
13
Chapter 1 Getting Started
Summary
In this chapter, you learned in general the why, what, and how of using the
PHP programming language in the development world. We introduced
why you want to use PHP, Nginx, and MySQL and their benefits. As
next steps, you learned how to install the Docker tool, which is an open
platform for developing, shipping, and running applications. Finally,
you saw why you needed the YAML files for your project to set up your
development environment.
In the next chapter, we will explain how programming languages use
variables to store and manipulate data and to build useful tools in PHP.
14
CHAPTER 2
PHP Fundamentals
In order to build useful tools in PHP, you need to know how to manipulate
data. Programming languages use variables to store and manipulate data.
In this chapter, you will learn how programming languages use
variables to store and manipulate data and to build useful tools in PHP.
Additionally, you’ll explore the following topics:
• Objects
Variables
PHP has a few rules when it comes to variables:
• A variable must start with the $ sign, followed by the
name of the variable.
<code>
<p>this is normal text</p>
<?php
echo '<p>This is created by php';
?>
<p>this is normal text again</p>
</code>
The code above shows three lines. The first is normal HTML, the
second is running PHP code, rendering HTML. The third is more HTML
but after/outside the PHP code snippet. You can go between PHP and
HTML as many times as you like within a .php file. This can get messy, so
you want to limit this to very clean and precise code elements. Now create
a file called vartest.php and open it up. Type this code into the file and
save it:
<code>
<?php
echo "<p>variable test</p>";
$color = "blue";
$item = "pants";
echo "Today I am using $item which happen to be the color
$color";
</code>
16
Chapter 2 PHP Fundamentals
Ok, let's catch up on what you are doing here. First, you are declaring
the PHP script with
<code>
<?php
</code>
The next line you use echo. This is a PHP command that makes up
one of the most basic ways to display text from PHP to the browser. It does
one thing: sends output to the browser or command prompt. Notice that
after echo, you use the double quote (“) as the delimiter to separate this
portion of text and begin the line of text you wish to output to the screen.
When you are done with the text, you end it with another double quote.
The double quote is the delimiter that marks the beginning and end of a
line of text you want to use. As humans, we can easily determine text or
a sentence that is written down or on a screen. Computers need special
markings, delimiters in this case, to determine where the text boundaries
are. This is true for the echo command or for setting a variable, as in the
next line. $color is the name of a variable you want to use and "blue" is
the value you are setting it to. In this particular case, $color is a variable
of type string. A string is any text that you want to use that will not be used
to compute, say, a mathematical value. Once you have the value of "blue"
set in $color, you can use echo to display it on the page. You do this again
with the variable $item when you set its value to "pants". You will notice
as well that each line of code ends with a semicolon (;). In PHP, this is how
you tell the interpreter to stop reading the line and move on. You will get
an error any time you leave out the ending semicolon.
17
Chapter 2 PHP Fundamentals
Speaking of errors, let’s go ahead and get comfortable with errors and
how they can be useful to us instead of annoyances.
<?php
error_reporting( E_ALL );
ini_set( "display_errors", 1);
Before you run this, let’s explain what you are doing.
error_reporting( E_ALL ); is telling PHP to display ALL errors. Here
is the full list of options available for error_reporting:
<?php
18
Chapter 2 PHP Fundamentals
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
<code>
Parse error: syntax error, unexpected token ">" in /var/www/
chapter2/vartest.php on line 8
</code>
Using this error, you can begin to hunt down the bug. This error is
saying that line 8 has an unexpected >. Take a look at line 8 of your code:
<code>
echo "<p>variable test</p>";
</code>
19
Chapter 2 PHP Fundamentals
This line looks perfectly fine to me. What PHP is telling us is that
you have done something, in this case set a delimiter for text, on the line
BEFORE line 8 and now the perfectly acceptable > on line 8 is unexpected.
You need to look at line 6 where you will find the closing delimiter of “
missing at the end of your text. Go ahead and add “ to the end of the line
and refresh your page, which should now render with no errors.
Now that you can create and assign variables, render text to the screen,
and trigger/understand errors that show up, let’s start building some
pages. This is the reason you picked up this book, right? Go back to your
Chapter2 directory and open the file main.php.
<code>
<?php
error_reporting( E_ALL );
ini_set( "display_errors",1);
$title = "Beginning PHP 8 & MySQL";
$content = "Here is the main content for this page";
$html ="
<!doctype html>
<html lang='en'><?php
<head>
<meta charset='utf-8'>
<title>$title</title>
<meta name='description' content='Basic HTML5 Page'>
<meta name='author' content='Your name'>
</head>
20
Chapter 2 PHP Fundamentals
<body>
$content
</body>
</html>";
echo $html;
</code>
These are the basic elements needed for a HTML 5 webpage with PHP
included. You are declaring that you want errors to be turned on at the
top, as you have done before. The next lines set two variables, one for the
title and one for the content. The rest of the file sets the variable $html
to the entirety of HTML that you want displayed on the page. Within this
code you see the $title and $content variables placed where you want to
display them on the page. Go ahead and open your browser to this page to
see how it looks. This can get a little redundant if you have many pages that
follow the same look and feel presented with the HTML. Therefore, you
will use this page as a template that you can call and just switch out the
values you want displayed. Open up main2.php in your editor.
<code>
<?php
//error_reporting( E_ALL );
//ini_set( "display_errors",1);
$title = "Beginning PHP 8 & MySQL";
$content = "Here is the main content for this page";
$html =include_once "inc/template2.php";
</code>
21
Chapter 2 PHP Fundamentals
Building on this example, let’s take it a step further and include multiple
PHP files in your template. In main2.php, change template.php to
template2.php and refresh the page.
In your case, you first include header.php, located within the inc/
directory. When you use this method of including PHP snippets around
the HTML in your file, you are essentially creating a template. This
template (main.php), if used in another file, will still include a header,
contents, and footer. Let’s create a file called second.php by copying the
main.php file and naming it second.php.
Now that you have come to an understanding with your templates on
how to separate them and use them to your advantage, let’s take a look
at your variables. So far you have been using variables for trivial content,
colors, and item names. What if you want to store someone’s name and
address? It’s perfectly correct to do something like this:
<code>
$firstName = "gunnard";
$lastName = "engebreth";
</code>
This works fine until you want to start passing this information around
between functions in your program. Basically, envision passing your friend
a handful of Skittles vs. a bag of Skittles. Your friend still gets the Skittles in
the end, but one way is clean, optimized, and all Skittles are guaranteed to
reach your friend. This brings us to objects.
Objects
In PHP, an object is a specific set of data as defined in a class. In the code
example above, you would say that the information would belong to a class
of User. You would define that class as such:
<code>
22
Chapter 2 PHP Fundamentals
<?php
class UserClass
/* User variables */
var $firstName;
var $LastName;
function getFirstName(){
echo $this->firstName;
}
function setLastName($lastName){
$this->lastName = $lastName;
}
function getLastName(){
echo $this->lastName;
}
}
</code>
23
Chapter 2 PHP Fundamentals
<code>
<?php
$title = "main3 php file";
require "UserClass.php";
$user = new UserClass;
$user->setFirstName = 'gunnard';
$user->setLastName = 'engebreth';
var_dump($user);
error_reporting( E_ALL );
ini_set( "display_errors",1);
$html =include_once "inc/template2.php";
</code>
24
Chapter 2 PHP Fundamentals
You have already reviewed what the first two lines do, so set up and set
the variable $user as a part of the class UserClass. The next two lines set
the first name and last name. If you run this script on the command line or
browser, you can verify this through the var_dump() function. Figure 2-2
shows what you should see.
25
Chapter 2 PHP Fundamentals
GET
POST
PUT
DELETE
PATCH
The PATCH method is used to apply partial
modifications to a resource.
You will be focusing on GET and POST but rest assured, you will be using
the others as you build your REST API.
Point your browser to http://localhost:8000/chapter2/main4.
php?pants=123. Notice in the URL you have main4.php?pants=123. When
the page loads, it should look like Figure 2-3.
26
Chapter 2 PHP Fundamentals
At the top is var_dump() and you can see that the info you have in
the URL is now available to you in PHP as the variable $userVars. This is
available to you through the HTTP verb GET and in PHP you use the global
variable $_GET. GET specifically allows for the transfer of data through the
URL. You can send multiple values as well. Change the URL to include
<code>
http://localhost:8000/chapter2/main4.php?pants=123&dog=poodle&f
ood=spaghetti
</code>
Refresh the page and you will now see that Pants, Dog, and Food have
values set to them. The other method of transmitting data from the user to
your code is using POST.
The POST verb behaves in nearly the same way but does not use the
URL, thereby keeping the data you are transmitting a bit more secure. In
order to see the POST functionality, open main5.php and take a look.
<code>
<?php
$userVars = $_POST;
$title = "main5 php file";
require "UserClass.php";
$user = new UserClass;
$user->setFirstName = 'gunnard';
$user->setLastName = 'engebreth';
27
Chapter 2 PHP Fundamentals
var_dump($userVars);
error_reporting( E_ALL );
ini_set( "display_errors",1);
$html =include_once "inc/template3.php";
</code>
The main things that changed in this code are that you are using the
PHP global $_POST instead of $_GET and you include template3.php. Let’s
look at the tempalte3.php file.
<code>
$content = include('contentPost.php');
</code>
<code>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_
SELF"]);?>" method="post">
<input type="text" id="firstName" name="firstName" />
<input type="text" id="lastName" name="lastName" />
<input type="submit" name="submit">
</code>
Here you see the differences in that allow you to use $_POST. You
define a form and set the action to the file (main5.php) itself. This code
you see allows for the form to be used in multiple places by dynamically
finding the name of the file that houses the form and putting it there.
$_SERVER['PHP_SELF'] is the file currently calling this script and
htmlspecialchars is a PHP function that removes HTML because it can
be used for malicious or evil intent. The two lines underneath declare the
firstname and lastname boxes to collect the users input. Finally, you have
a Submit button that triggers the form to be used by your code. Go ahead
and fill it out and then look at the resulting page (Figure 2-4).
28
Chapter 2 PHP Fundamentals
You can see in your var_dump that the variables for first name and last
name came through, and if you look at your URL, you see that it is clean and
no variables are listed. In your examples, you used GET and POST to submit
data to your PHP. Technically, you could use GET to submit this form as well,
but you should really not do that. These two methods, GET and POST, are (as
listed above) part of a larger group of verbs that are used currently in modern
development in APIs. An application programming interface (API) is a method
of allowing access for developers to interact with an application. Think about
it this way: stock tickers, tweet streams, an Instagram plugin for WordPress--
these all are individual pieces of software that connect to other things:
29
Chapter 2 PHP Fundamentals
“update” methods that can alter a users’ status or swap out profile pictures,
for example. DELETE is primarily used to remove or destroy data from the
API. While it is completely possible to only use GET and POST for an API,
the separation of verbs and (as you will see) routes based off of these verbs
will allow for a much easier and better experience for the developer using
the given API. If you are using POST to create, update, delete, and search,
this can get messy because you will need to not only look at whether the
request is GET/POST but now also a new variable needs to be set to specify
the intended action (create, update, delete, search, etc.). Clear and direct
methods of communication not only help humans communicate but can
keep things straightforward with software, too.
Summary
Let’s review the ideas you’ve learned so far.
a.
error_reporting( E_ALL );
b.
ini_set( "display_errors", 1);
30
Chapter 2 PHP Fundamentals
In the next chapter, you will learn how to declare and use classes and
functions (including traits, which is what a class is to an object). Also,
object-oriented programming (OOP) will be explained.
31
CHAPTER 3
Functions, Classes,
and Traits
So far, you have been using PHP for simple top-down scripting.
In this chapter, you will learn how to declare and use classes and
functions (including class definitions, visibility, inheritance, and traits).
Also, object-oriented programming (OOP) will be introduced and
explained.
The real power of PHP comes with the ability to declare and use
classes and functions. As a quick overview, classes are (as you saw in the
last chapter) definitions for objects to use when being created. The class
definitions then turn into objects that you can use to store and manipulate
data. Functions are reserved words within PHP that you declare, define,
and call in order to do small or complex tasks. The reason you separate out
these tasks into functions is so that you can abstract them and their usage.
Abstract is a fancy way of allowing for a function to be called by multiple
sources for one purpose. Instead of writing a function in multiple classes to
do the exact same thing, you can set that function apart in a class and call
it whenever you need. The duplication of code is one thing to look out for
when refactoring or even working through your logic.
With these concepts in mind, this chapter will focus on the world of
OOP, which models the application and development around real-world
objects such as users, cars, colors, or even vegetables.
• Class definitions
• Class visibility
• Class inheritance
OOP
The three basic concepts in object-oriented programming are
34
Chapter 3 Functions, Classes, and Traits
<code>
<?php
class UserClass
{
/* User variables */
var $firstName;
var $LastName;
function getFirstName(){
echo $this->firstName;
}
function setLastName($lastName){
$this->lastName = $lastName;
}
35
Chapter 3 Functions, Classes, and Traits
function getLastName(){
echo $this->lastName;
}
}
</code>
Class definitions begin with the PHP keyword class followed by the
name and then a pair of curly braces. Within these curly braces is where
the properties (variables) and methods (functions) belonging to the
class are defined. Within classes, functions are referred to as methods.
This is a whisky/bourbon situation. All bourbon is whiskey, but not all
whisky is bourbon. All methods are functions, but not all functions you
see are methods. The name of the class, in your case UserClass, has a few
restrictions as to how it can be named:
PHP has many reserved words. You have already seen class, function,
and any PHP function such as var_dump or echo used in PHP. These words
cannot be reused as variables or names for what is dubbed “userland” use.
Any class, method, function, or variable created by a user and not built into
PHP is deemed “userland.” This is not necessarily as derogatory as it may
sound but just a way of keeping the two worlds separate. In your example,
you have variable declarations for
<code>
/* User variables */
var $firstName;
var $LastName;
</code>
36
Chapter 3 Functions, Classes, and Traits
Class Visibility
Class properties and methods have what is referred to as visibility. This
visibility can be defined by prefixing the declaration of the property. For
example,
<code>
public $firstName = 'Abraham';
protected $lastName = 'lincolin';
private $nickName = 'beardyface';
</code>
In the example class above, you use var to declare your property,
which defaults to public. The reasoning for visibility levels is for control
over how data flows within your code. PHP allow you to do something
like this:
<code>
$user = getUser($userId);
function showUserName() {
$user = getUser(4);
var_dump($user);
}
var_dump($user);
showUserName();
</code>
Here you are getting quite sloppy with your variables and logic, and
PHP is trusting that you know what you are doing. PHP provides three
levels to keep internal function variables and external variables separate
from one another: public, protected, and private.
37
Chapter 3 Functions, Classes, and Traits
Public
Public properties have no restrictions for calling them in any scope. This
means that a public property of an object can both be retrieved and also
modified anywhere in code. As stated, this is the default behavior when
declaring a class property using var. While this is acceptable in terms of
functional PHP code, you should define the visibility of a property when it
is declared.
Protected
The second level is protected, which means that the class that they are
declared in or any class that extends them can access the property.
Private
The last level, private, is like protected but takes it up a notch by only
allowing access to the class it is defined in. Any subclass or extended class
cannot access this property.
There is more to visibility, such as making properties and methods
MORE visible and extending them as well. These topics are for another day
but if you wish to read up on them, php.net has great information on all
things visibility.
<code>
38
Chapter 3 Functions, Classes, and Traits
39
Chapter 3 Functions, Classes, and Traits
<code>
<?php
// Parent class
abstract class Candy {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function slogan() : string;
}
// Child classes
class Skittle extends Candy {
public function slogan() : string {
return "$this->name! - Taste the rainbow!";
}
}
40
Chapter 3 Functions, Classes, and Traits
In this example, you define the abstract parent class Candy with
a property for the name and two methods. The construct method is
standard and takes a string for name. The second is the slogan method,
which is (for all intents and purposes) empty and returns a string. What
you are doing with this is carving out the name slogan in the class but
allowing the child classes to define what that method is actually doing.
You are keeping consistency within the objects you create by doing this. As
long as the object is created from a class that extends Candy, you know that
there is a slogan method, and if you are the one that extends the class, you
know that you need to define what this method does.
41
Chapter 3 Functions, Classes, and Traits
Constants
Classes also can have constants. Constants are properties or methods
that can be defined within a class and used (depending on visibility) from
anywhere.
<code>
<?php
class MessageClass {
const EXIT_MESSAGE = "Thank you for coming to my
TEDDY talk!";
public function thankyouBye() {
echo self::EXIT_MESSAGE;
}
}
There are two ways in which this constant can be accessed. From
within the class, self:: can be used, which you did in your example.
The other way is to reference the class name and the double ::, such
as MessageClass::EXIT_MESSAGE. Constants can be useful in the
organization of properties and ensuring continuity of values across your
application. In your example, you have a message class to house all of
your application messages. This way you only have one class to call and
one class to ever change if there is a need to update a message. If there are
one-off messages, you can always extend the class and adjust the verbiage
from there. The main point of using constants in this way is to keep your
data structured and organized for the best use as you develop and to keep
42
Chapter 3 Functions, Classes, and Traits
Constructs
Classes offer constructors and destructors. The former is called and
“constructs” at the time a new object is created and the latter “destructs” as
soon as there are no other references to a particular object. A constructor
method looks like this:
<code>
<?php
class UserClass {
function __construct() {
print "In UserClass constructor\n";
}
}
</code>
Note that the construct() method has __ in front of the name. Prior to
PHP 8, classes with a method named the same as the class would interpret
that method as the constructor. This will now result in an E_DEPRECATED
error but still run as a constructor. If both __construct() and a method
with the same name as the class are defined, __construct() will be called.
Constructors are used to set certain parameters to properties when
new objects are created. This can easily be done now in PHP 8 with
constructor property promotion.
<code>
<?php
class Point {
public function __construct(
43
Chapter 3 Functions, Classes, and Traits
}
}
</code>
<code>
<?php
class UserClass {
function __destruct() {
print "Destroying " . __CLASS__ ."\n";
}
}
</code>
Traits
Then there are traits. Think about a trait as what a class is to an object, the
trait is to a class. You can define several methods in a trait and use them in
several different classes as long as the classes reference back to the trait.
The reason you use traits in PHP is because PHP is a single inheritance
language. This means that while you can define a class and all of its
methods and any subclass you extend from that will have access to those
methods, you can’t reach over to another class and borrow a method.
44
Chapter 3 Functions, Classes, and Traits
The subclass cannot inherit methods from another class. To prevent you
from duplicating code all over the place, you can reference a trait from
multiple subclasses to utilize a single method. Here is a simple example:
<code>
<?php
trait userFunctions {
public function message1() {
echo "user message1";
}
}
class UserClass {
use userFunctions;
}
class UserClass2 {
use userFunctions;
}
This prints out the message “user message1 user message1” from two
separate classes. This is very useful when dealing with large systems that
share functionality but not necessarily the same data.
Lastly, we must discuss namespaces and their function within OOP.
45
Chapter 3 Functions, Classes, and Traits
Namespaces
Namespaces allow for the labeling of classes so that when you reference
them within your code, you can specify the class you wish to use from
within its namespace. You can also use namespaces to group together
classes for better organization. Namespaces also allow for the use of the
same name in different classes. Here is how a namespace is declared:
<code>
<?php
namespace Pants;
</code>
<code>
<?php
Namespace Pants;
class PantsMaker {
$color = 'blue';
$size = 'large';
46
Chapter 3 Functions, Classes, and Traits
You can also just include this PHP file within the same namespace and
there is no need for the beginning Pants\.
<code>
<?php
namespace Pants;
$thesePants = new PantsMaker();
echo $thesePants->pantsLabel('leeevi');
</code>
There is also the ability to alias a namespace for ease of use or better
code management.
<code>
namespace Pants as P;
$thesePants = new P\PantsMaker();
echo $thesePants->pantsLabel('leeevi');
</code>
47
Chapter 3 Functions, Classes, and Traits
Summary
Let’s review what you now know about OOP.
In the next chapter, you will learn how to work with data and data types
such as Bool, Int, Float, and Array.
48
CHAPTER 4
• Special types
World” within a variable, you choose the type string over the type integer.
Why? A string is a sequence of characters while an integer is a non-decimal
number between -2,147,483,648 and 2,147,483,647. For practicality
purposes, using a string makes more sense, and if you try to assign “Hello
World” to an integer, PHP will kindly tell you that you cannot do such a thing.
Here are the eight basic data types used to create variables in PHP:
50
Chapter 4 Data and Data Types
• Boolean
• Integer
• Float
• String
Boolean
A bool or boolean type is the simplest type. Bool expresses a “truth” value
of either true or false.
To specify a bool literal, use the constants true or false. Both are case-
insensitive.
<?php
$foo = True; // set the value TRUE to $foo
?>
<?php
if ($isTuesday) {
echo "Taco Tuesday!!";
}
?>
51
Chapter 4 Data and Data Types
Integer
An int is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Integers can be specified in four different bases:
1) Decimal (base 10) [ 1, 2, 3, 4, 5, 6, etc.]
<?php
$a = 1234; // decimal number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0o123; // octal number (as of PHP 8.1.0)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
$a = 1_234_567; // decimal number (as of PHP 7.4.0)
?>
Float
A float (floating point number) is a number with a decimal point or a
number in exponential form.
<?php
$a = 1.234;
$b = 1.2e3;
52
Chapter 4 Data and Data Types
$c = 7E-10;
$d = 1_234.567; // as of PHP 7.4.0
?>
String
A string is a sequence of characters, like “Hello World!”.
A string can be any text inside quotes. You can use single or
double quotes.
<?php
$foo = "Hello World!";
$bar = 'Hello World!';
?>
• Single quotes
• Double quotes
• Heredoc syntax
• Nowdoc syntax
53
Chapter 4 Data and Data Types
<?php
echo 'this is a single quoted string';
54
Chapter 4 Data and Data Types
When using double quotes ("), PHP interprets the following escape
sequences for special characters:
Sequence Meaning
55
Chapter 4 Data and Data Types
A third method to create a string data type in PHP is with the heredoc
syntax: <<< . This method is especially useful for large amounts of
preformatted text. To use the heredoc, you simply start with this operator,
<<<, and afterwards it is followed by an identifier that marks the name
or reference of this string and then a newline. The string comes next and
then the same identifier from the beginning is used to close or end the
quotation. It looks something like this:
<?php
echo <<<MYIDENTIFIER
Here is
The text that
I want to display
MYIDENTIFIER;
?>
<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>
56
Chapter 4 Data and Data Types
<?php
Echo <<<'FOOBAR'
Text that will not get parsed,
This will just show up
FOOBAR
?>
<?php
$tea = "earl grey";
57
Chapter 4 Data and Data Types
<?php
$great = 'fun';
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[4][3]}";
58
Chapter 4 Data and Data Types
// Works.
echo "This works: " . $arr['foo'][3];
echo "This is the value of the var named by the return value of
getName(): {${getName()}}";
echo "This is the value of the var named by the return value of
\$object->getName(): {${$object->getName()}}";
<?php
class foo {
var $bar = 'I am bar.';
}
59
Chapter 4 Data and Data Types
• substr()
• strlen()
• str_replace()
• trim()
• strpos()
• strtolower()
• strtoupper()
• is_string()
• strstr()
substr( )
string substr(string string, int start[, int length] );
60
Chapter 4 Data and Data Types
When calling the function, you can use either positive or negative
numbers. A positive number gets the string from the start position to the
end of the string. A negative start number gets the string from the end
of the string minus the start characters to the end of the string. Look at
chapter4-substring.php.
substr($comment, 5, -10);
//returns 'product'
5 signifies the starting character point (p) and -10 determines the
ending point (count 10 places backwards starting from the end of the
string).
61
Chapter 4 Data and Data Types
strlen( )
strlen() is used for checking the length of a string.
<?php
$foo = "bar";
str_replace( )
Many times, with strings, being able to find and replace a substring is
handy. With str_replace(), this is made easy for us.
62
Chapter 4 Data and Data Types
<?php
$strings = array (
'You like to have a snazzy time',
'You are a really snazzy person',
'Would you like to drink a cup of coffee?'
);
$search = array (
'snazzy',
'cup',
'person',
'coffee'
);
$replace = array (
'great',
'bottle'',
'dude',
'Dark brown stuff'
);
trim( )
Dealing with unknown input is tricky, and this is where trim() comes in
handy. The trim() function strips away unwanted spaces from the left,
right, or both sides of a string. You can also specify which characters you
would like to strip.
<?php
$trimit = 'junk awesome stuff junk';
63
Chapter 4 Data and Data Types
print_r ( $trimmed );
// awesome stuff
?>
strpos( )
The function strpos() operates in a similar fashion to strstr(), except,
instead of returning a substring, it returns the numerical position of a
needle within a haystack.
// 13
This function accepts a single character as the needle, but it can accept
a string of any length. The optional offset parameter determines the point
within the haystack to start searching.
This code echoes the value 11 to the browser because PHP started
looking for the character m at position 3.
64
Chapter 4 Data and Data Types
In any of these cases, if the needle is not in the string, strpos() will
return false. To avoid strange behavior, you can use the === operator to test
return values. See chapter4-strpos.php.
<?php
$awesome = "Super Awesome!";
// Not found
?>
strtolower( )
Very often in PHP you need to compare strings or correct capitalization
when people SHOUT or do odd things. In order to compare strings, you
want to make sure they are the same case. You can use strtolower() for
this purpose. Let’s use a function created with strtolower() to calm down
an angry person.
<?php
function calm_down($string) {
65
Chapter 4 Data and Data Types
strtoupper( )
strtoupper() is also quite popular for many of the reasons listed above
but in reverse, meaning it takes a lowercase or mixed case string and sets it
to all upper case. Let’s change things up and create a wake-up function to
get your workers going in the morning.
<?php
function wake_up($string) {
is_string( )
is_string() is used to check if a value is a string. Let’s take a look at this
within an if() statement to take an action on strings in one way and non-
strings in another. is_string() returns true or false.
<?php
if (is_string ( 7 )) {
echo "Yes";
} else {
echo "No";
66
Chapter 4 Data and Data Types
}
// No
strstr( )
Last but not least is the strstr() function. The function strstr() can
be used to find a string or character match within a longer string. This
function can be used to find a string inside a string, including finding a
string containing only a single character.
<?php
$url = 'vegibit.com';
67
Chapter 4 Data and Data Types
echo $url;
// https://www.vegibit.com
?>
• Array
• Object
Array
An array in PHP is actually an ordered map. A map is a type that associates
values to keys. This type is optimized for several different uses; it can be
treated as an array, list (vector), hash table (an implementation of a map),
dictionary, collection, stack, queue, and probably more. Since array values
can be other arrays, trees and multidimensional arrays are also possible.
Explanations of these data structures are beyond the scope of this manual,
but we’ll provide at least one example for each of them. For more information,
look for the considerable literature that exists about this broad topic.
An array in PHP is a type that associates values to keys. By default,
PHP assigns the keys as numbers starting at 0 and going to the size of your
array. See chapter4.php.
<?php
$myArray[0] = "first";
68
Chapter 4 Data and Data Types
$myArray[1] = "Second";
$myArray[2] = "3rd";
var_dump($myArray);
?>
array(3) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
[2]=>
string(3) "3rd"
}
PHP also gives you the option to have specifically assigned keys that may
have more meaning to your application. They are called associative arrays.
<?php
$myArray['fruit'] = "apple";
$myArray['vegetable'] = "carrot";
$myArray['color'] = "blue";
var_dump($myArray);
?>
array(3) {
["fruit"]=>
string(5) "apple"
["vegetable"]=>
string(6) "carrot"
["color"]=>
string(4) "blue"
}
69
Chapter 4 Data and Data Types
You can create arrays with multiple dimensions as well. You can think
of this like a television show comprised of the title “Strangest Things”
divided into seasons with individual episodes. As a variable in PHP, it
could look like this:
<?php
$strangestThings['season1']['episode1'] = "The Beginning";
//or
$strangestThings[0][0] = "The Beginning";
$strangestThings['season1']['episode3'] = "The Third Episode";
var_dump($strangestThings);
?>
array(2) {
["season1"]=>
array(2) {
["episode1"]=>
string(12) "The Beginning"
["episode3"]=>
string(17) "The Third Episode"
}
[0]=>
array(1) {
[0]=>
string(13) "The Beginning"
}
}
70
Chapter 4 Data and Data Types
Object
Objects as well as classes make up the main components of object-
oriented programming (OOP). You can think of a class as the template or
structure that an object will use when the new object is created and used.
When an object datatype is created as a variable, let’s say $myCar, it will
have all of the properties and functionality of the $car class, including
$model, $color, $price, and so on.
When the individual objects are created, they inherit all the properties
and behaviors from the class, but each object will have different values for
the properties.
Let’s assume you have a class named Car. A Car can have properties
like model and color. You can define variables like $model and $color to
hold the values of these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created,
they inherit all the properties and behaviors from the class, but each object
will have different values for the properties.
If you create a __construct() function, PHP will automatically call this
function when you create an object from a class.
• NULL
• Resource
NULL
NULL is a special value that represents a variable with no value. NULL is
the only value that can possibly go in.
71
Chapter 4 Data and Data Types
(chapter4-1.php)
<?php
$var = NULL;
if(!isset($var)){
echo 'Null value' ;
}
?>
Null value
resource
Resources are not exactly a data type in PHP because they are mainly used
to store some function calls or as references to external PHP resources.
Summary
In this chapter, you learned that in PHP there are different data types
like scalar types (predefined), compound types (user-defined), and
special types.
72
Chapter 4 Data and Data Types
You also learned that PHP data types can be alphanumeric, whole
numbers, floating points, and Boolean. You focused especially on
strings, which are a very useful type in PHP and you will use them
often. Remember that the power of strings comes in the many different
manipulations that can be performed and the many different prebuilt
string functions that are available.
In the next chapter, you will learn about PHP form data handling
and you will see how to create and use forms to get form data using PHP
superglobals such as $_GET and $_POST.
73
CHAPTER 5
Form Data
In this chapter, you will learn how to create and manage forms in PHP
using the POST and GET methods.
You will explore three superglobals: $_POST, $_GET, and $_REQUEST.
$_POST and $_GET are the two most common ways of receiving user input
in PHP. $_REQUEST is lesser used.
This chapter consists of the following sections:
(basicForm.php)
76
Chapter 5 Form Data
<html>
<body>
</body>
</html>
This form takes the user input of name and email and sends them via
POST to functions.php. The “method” is set by the method setting and
where you are sending these values is set at the action setting. If you open
up functions.php, you can see what happens next.
<?php
echo "Thank you {$_POST['name']}. I will email you at {$_
POST['email']}";
?>
<br />
<a href="basicForm.php">back</a>
This code takes (and assumes the validity of ) the two POST variables
sent from your form and prints them to the screen. You see name="name"
and name="email" get sent over to functions.php and be retrieved with
$_POST['name'] or $_POST['email']. If you change the name of email
in the form page from name="email" to name="myEmail", then you would
have to refer to it as $_POST['myEmail']. Let’s try something real quick.
Instead of putting your name in the “name” field, try typing
<h1>pants</h1>
77
Chapter 5 Form Data
This is not the result the developer (you) were thinking about when
creating this form. As a developer, you must always be thinking of not only
the exact use case for your code; the fringe, edge cases, and worst cases
must be considered. Users are very dependable and will consistently use
applications the “right” way but there are cases in which the previous
example can happen. Hopefully this happens because of a one-off mistype,
but the reality is that more and more often attackers use forms like the one
you built to utilize the lack of security measures to gain entrance into your
system. Security must be at the forefront of a developer’s mind, no matter
where you work or how secure you think you may be.
Let’s start to mitigate this situation.
Open up functions.php and add these lines to make the code look
like this:
<?php
78
Chapter 5 Form Data
<?php
$emailErr= null;
$name = filter_var($_POST['name'], FILTER_SANITIZE_FULL_
SPECIAL_CHARS);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (!$emailErr) {
echo "Thank you {$name}. I will email you at {$email}";
} else {
echo $emailErr;
}
?>
79
Chapter 5 Form Data
<br />
<a href="basicForm.php">back</a>
<?php
$emailErr= null;
$name = filter_var($_POST['name'], FILTER_SANITIZE_FULL_
SPECIAL_CHARS);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
80
Chapter 5 Form Data
if (!$emailErr) {
echo "Thank you {$name}. I will email you at {$email}";
} else {
echo $emailErr;
}
?>
<br />
<a href="basicForm.php?name=<?= $name ?>&email=<?=
$email?>">back</a>
Here you are adding the $name and $email variables to the URL so that
you can use them when you get back to shortForm.php. What is with <?=,
though? This is how you can use PHO with its short open option. Instead
of typing <?php when you want to use PHP code within HTML to do
something simple, you can use the short open <?= and the = means echo.
So, with this in your toolbox, you can quickly put the $name and $email
variables where you need to in the URL to use the $_GET variable back on
the basicForm.php page. Go ahead and open that file up, too, and add
these lines:
<?php
if (isset($_GET)) {
if (isset($_GET['name'])) {
$name = $_GET['name'];
}
if (isset($_GET['email']) {
$email = $_GET['email'];
}
}
81
Chapter 5 Form Data
<html>
<body>
<form action="functions.php" method="post">
Name: <input type="text" name="name" value="<?= $name; ?>"><br>
E-mail: <input type="text" name="email" value="<?= $email;
?>"><br>
<input type="submit">
</form>
</body>
</html>
The form page will now check to see if there are any variables set
within the $_GET super global. If there are, it checks if $_GET['name'] and
$_GET['email'] are set. If there is anything in there, it sets them to $name
and $email, respectively. Next, it checks if $name or $email have been set
or not. This is a ternary if statement. Instead of typing
if ($name != "" ) {
$name = $name;
} else {
$name = "";
}
82
Chapter 5 Form Data
In the input box you use the value setting to add the name or email you
just received (or not) from $_GET via the URL. Now that you can get user
information and pass it back to your own scripts, you can fully interact
with users. Using the $_GET and $_POST superglobals gets you familiar with
arrays, specifically associative arrays.
Summary
In this chapter, you learned about PHP form data handling. You learned
how to create and use forms to get form data using PHP superglobals such
as $_GET and $_POST.
In the next chapter, you will learn more and take a deeper look into
arrays, which are used to hold in a single variable multiple values of a
similar type.
83
CHAPTER 6
Arrays
In the previous chapters, you learned how to deal with PHP variables. In
this chapter, we will teach you how to create and manage PHP arrays.
Say you need to hold multiple values of a similar type in a single
variable, without creating additional variables to store those values. How
would you do this? By using PHP arrays.
This chapter consists of the following sections:
array(
key => value,
key2 => value2,
key3 => value3,
...
)
$city=array("Rome","Naples","Milan");
$city[0] = "Rome";
$city[1] = "Naples";
$city[3] = "Milan";
Actual PHP code with an associative array looks like the following:
Chapter6/firstArray.php
<?php
$array1 = array(
"foo" => "bar",
"bar" => "foo",
);
var_dump($array1);
echo '<br />';
var_dump($array2);
86
Chapter 6 Arrays
The first part, array(2), tells you that the variable you are using,
var_dump, is of type array. The 2 indicates how many elements are held
within this array. The next part is the key=>value pair listing. The key is
in the square brackets and the value is to the right of the => sign. Looking
to the direct right of => you see string(3), which tells you that the value
in the key=>value pair is a string with a length of 3 ("bar"). Let’s look at
firstArray2.php to see some examples using different types of variables.
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>
Notice you have data of types string and int within this array. So far you
have used the key=>value relationship to define your arrays, but what if
you don’t “need” a key? For example, what if you are just using the array to
store the first names of preferred customers. You would not want to use
87
Chapter 6 Arrays
This would not work. First, you can’t successfully use the same key for
multiple values. And second, it is just useless. PHP automatically assigns a
numeric key when one is not defined by the user.
firstArray3.php
<?php
$array = array("foo", "bar", "hello", "world");
var_dump($array);
The output is
You can see that instead of a key that you defined, PHP uses numbers in its
place. Notice that the array starts at 0 instead of 1. With all the many programming
languages and their differences, they all agree on one thing: arrays start at 0.
If you have been following along so far, you may be wondering if you
can have an array WITHIN an array. The answer is yes. They are called
multidimensional arrays. Take a look at firstArray4.php.
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foobar"
)
)
);
88
Chapter 6 Arrays
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
The output is
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
<?php
$cars = array (
array("Subaru",21,17),
array("Toyota",13,12),
array("Lexus",6,8),
array("Ford",14,10)
);
89
Chapter 6 Arrays
Here you see that you can create a two-dimensional array using
data from a used car lot. You are keeping track of the car brand, units
available, and units sold. Your main array contains four separate arrays
with the specific data. Cars is an array with the first element being an array
containing Subaru, 21, and 17. To access Subaru, you use
$cars[0][0];
This means, within the $cars array, you want the first ( [0] ) element
of the first ( [0] ) element. If you want to access 21, you use $cars[0][1],
meaning you want the second element ( [1] ) of the first ( [0] ) element.
Whenever you need to work through data that is stored in an array, for
loops are a great solution. Here you iterate through the array and print out
the needed information:
90
Chapter 6 Arrays
Definition
$emp = array
(
array(1,"Luna",10000),
array(2,"Leo",20000),
array(3,"Neve",30000)
);
91
Chapter 6 Arrays
Let’s now introduce some of the most used and common PHP Array
functions.
92
Chapter 6 Arrays
array_change_key_case
Changes the case of all keys in an array
array_chunk
Splits an array into chunks
Chunks an array into arrays with length elements. The last chunk may
contain less than the length elements.
Parameters
array
The array to work on
length
The size of each chunk
preserve_keys
93
Chapter 6 Arrays
When set to true, keys will be preserved. The default is false, which will
reindex the chunk numerically.
Return values
Returns a multidimensional numerically indexed array, starting with 0,
with each dimension containing length elements
array_column
Returns the values from a single column in the input array
94
Chapter 6 Arrays
Return values
Returns an array of values representing a single column from the
input array
array_combine
Creates an array by using the values from the keys array as keys and the
values from the values array as the corresponding values
Parameters
keys
Array of keys to be used. Illegal values for a key will be converted to
a string.
values
Array of values to be used
Return values
Returns the combined array or false if the number of elements for each
array isn’t equal
array_count_values
array_count_values() returns an array using the values of array as keys
and their frequency in array as values.
Parameters
array
The array of values to count
Return values
Returns an associative array of values from an array as keys and their
count as value
95
Chapter 6 Arrays
array_diff_assoc
Computes the difference of the arrays with an additional index check
Unlike array_diff(), the array keys are also used in the comparison.
Parameters
array
The array to compare from
arrays
Arrays to compare against
Return values
Returns an array containing all the values from the array that are not
present in any of the other arrays
array_diff_key
Computes the difference of arrays using keys for comparison
96
Chapter 6 Arrays
array_diff_uassoc
Computes the difference of the arrays with an additional index check,
which is performed by a user-supplied callback function. Unlike array_
diff(), the array keys are used in the comparison.
Return values
Returns an array containing all the entries from the array that are not
present in any of the other arrays
array_diff_ukey
Compares the keys from the array against the keys from arrays and returns
the difference. This function is like array_diff(), except the comparison
is done on the keys instead of the values.
97
Chapter 6 Arrays
Return values
Returns an array containing all the entries from the array that are not
present in any of the other arrays
array_diff
Computes the difference of arrays
Compares an array against one or more other arrays and returns the
values in the array that are not present in any of the other arrays
Parameters
array
The array to compare from
arrays
Arrays to compare against
98
Chapter 6 Arrays
Return values
Returns an array containing all the entries from the array that are not
present in any of the other arrays. Keys in the array are preserved.
array_fill_keys
Fills an array with the value of the value parameter, using the values of the
keys array as keys
Parameters
keys
Array of values that will be used as keys. Illegal values for a key will be
converted to a string.
value
Value to use for filling
Return values
Returns the filled array
array_fill
Fills an array with values
Fills an array with count entries of the value of the value parameter,
with keys starting at the start_index parameter
Parameters
start_index
The first index of the returned array. If start_index is negative, the
first index of the returned array will be start_index and the following
indices will start from 0 (see example).
99
Chapter 6 Arrays
count
Number of elements to insert. Must be greater than or equal to zero.
value
Value to use for filling
Return values
Returns the filled array
array_filter
Filters elements of an array using a callback function
Iterates over each value in the array, passing them to the callback
function. If the callback function returns true, the current value from the
array is returned into the result array.
Array keys are preserved and may result in gaps if the array was
indexed. The result array can be reindexed using the array_values()
function.
Parameters
array
The array to iterate over
callback
The callback function to use. If no callback is supplied, all empty
entries of array will be removed. See empty() for how PHP defines empty
in this case.
mode
Flag determining what arguments are sent to callback:
ARRAY_FILTER_USE_KEY
Passes the key as the only argument to callback instead of the value
ARRAY_FILTER_USE_BOTH
100
Chapter 6 Arrays
array_flip
Exchanges all keys with their associated values in an array
array_intersect_assoc
Computes the intersection of arrays with an additional index check
101
Chapter 6 Arrays
array_intersect_key
Computes the intersection of arrays using keys for comparison
array_intersect_uassoc
Computes the intersection of arrays with an additional index check and
compares indexes by a callback function
102
Chapter 6 Arrays
Return values
Returns the values of array whose values exist in all of the arguments
array_intersect_ukey
Computes the intersection of arrays using a callback function on the keys
for comparison
103
Chapter 6 Arrays
arrays
Arrays to compare keys against
key_compare_func
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less
than, equal to, or greater than the second.
Return values
Returns the values of array whose keys exist in all the arguments
array_intersect
Computes the intersection of arrays
array_is_list
Checks whether a given array is a list
104
Chapter 6 Arrays
array_key_exists
Checks if the given key or index exists in the array
array_key_first
Gets the first key of an array without affecting the internal array pointer
Parameters
array
An array
Return values
Returns the first key of array if the array is not empty or null otherwise
105
Chapter 6 Arrays
array_key_last
Gets the last key of an array without affecting the internal array pointer
Parameters
array
An array
Return values
Returns the last key of array if the array is not empty or null otherwise
array_keys
Returns all the keys or a subset of the keys of an array
array_keys() returns the keys, numeric and string, from the array. If
a search_value is specified, then only the keys for that value are returned.
Otherwise, all the keys from the array are returned.
Parameters
array
An array containing keys to return
search_value
If specified, then only keys containing this value are returned.
strict
Determines if the strict comparison (===) should be used during
the search.
Return values
Returns an array of all the keys in array
106
Chapter 6 Arrays
array_map
Applies the callback to the elements of the given arrays
107
Chapter 6 Arrays
array_merge_recursive
Merges one or more arrays recursively
array_merge
Merges one or more arrays
108
Chapter 6 Arrays
Values in the input arrays with numeric keys will be renumbered with
incrementing keys starting from zero in the result array.
Parameters
arrays
Variable list of arrays to merge
Return values
Returns the resulting array. If called without any arguments, returns an
empty array.
array_multisort
Sorts multiple or multi-dimensional arrays
array1_sort_flags
Sorts options for the previous array argument
Sorting type flags:
SORT_REGULAR compares items normally (doesn’t change types).
SORT_NUMERIC compares items numerically.
SORT_STRING compares items as strings.
SORT_LOCALE_STRING compares items as strings, based on the current
locale. It uses the locale, which can be changed using setlocale().
SORT_NATURAL compares items as strings using “natural ordering” like
natsort().
SORT_FLAG_CASE can be combined (bitwise OR) with SORT_STRING or
SORT_NATURAL to sort strings case-insensitively.
This argument can be swapped with array1_sort_order or omitted
entirely, in which case SORT_REGULAR is assumed.
rest
More arrays, optionally followed by sort order and flags. Only elements
corresponding to equivalent elements in previous arrays are compared. In
other words, the sort is lexicographical.
Return values
Returns true on success or false on failure
109
Chapter 6 Arrays
array_pad
Pada an array to the specified length with a value
array_pop
Pops the element off the end of array
array_pop()
Note This function will reset() the array pointer of the input array
after use.
110
Chapter 6 Arrays
Parameters
array
The array to get the value from
Return values
Returns the value of the last element of array. If the array is empty (or is
not an array), null will be returned.
array_product
Calculates the product of values in an array
Parameters
array
The array
Return values
Returns the product as an integer or float
array_push
Pushes one or more elements onto the end of array
<?php
$array[] = $var;
?>
111
Chapter 6 Arrays
If you use array_push() to add one element to the array, it’s better
to use $array[] = because in that way there is no overhead of calling a
function.
Parameters
array
The input array
values
The values to push onto the end of the array
Return values
Returns the new number of elements in the array
array_rand
Picks one or more random keys out of an array returns the key (or keys) of
the random entries.
112
Chapter 6 Arrays
array_reduce
Iteratively reduces the array to a single value using a callback function
array_reduce(array $array, callable $callback, mixed
$initial = null): mixed
Parameters
array
The input array
callback
callback(mixed $carry, mixed $item): mixed
carry
Holds the return value of the previous iteration; in the case of the first
iteration, it instead holds the value of initial.
item
Holds the value of the current iteration
initial
If the optional initial is available, it will be used at the beginning of
the process, or as a final result in case the array is empty.
Return values
Returns the resulting value. If the array is empty and initial is not
passed, array_reduce() returns null.
array_replace_recursive
Replaces elements from passed arrays into the first array recursively
113
Chapter 6 Arrays
created in the first array. If a key only exists in the first array, it will be left
as is. If several arrays are passed for replacement, they will be processed in
order, the later array overwriting the previous values.
array_replace_recursive() is recursive: it will recurse into arrays
and apply the same process to the inner value.
When the value in the first array is scalar, it will be replaced by the
value in the second array, whether its scalar or array. When the value
in the first array and the second array are both arrays, array_replace_
recursive() will replace their respective value recursively.
Parameters
array
The array in which elements are replaced
replacements
Arrays from which elements will be extracted
Return values
Returns an array or null if an error occurs
array_replace
Replaces elements from passed arrays into the first array
114
Chapter 6 Arrays
Parameters
array
The array in which elements are replaced
replacements
Arrays from which elements will be extracted. Values from later arrays
overwrite the previous values.
Return values
Returns an array or null if an error occurs
array_reverse
Return an array with elements in reverse order
Parameters
array
The input array
preserve_keys
If set to true, numeric keys are preserved. Non-numeric keys are not
affected by this setting and will always be preserved.
Return values
Returns the reversed array
array_search
Searches the array for a given value and returns the first corresponding key
if successful
115
Chapter 6 Arrays
haystack
The array
strict
If the third parameter, strict, is set to true, the array_search()
function will search for identical elements in the haystack. This means it
will also perform a strict type comparison of the needle in the haystack,
and objects must be the same instance.
Return values
Returns the key for needle if it is found in the array and false otherwise
If needle is found in haystack more than once, the first matching key
is returned. To return the keys for all matching values, use array_keys()
with the optional search_value parameter instead.
array_shift
Shifts an element off the beginning of array
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from 0 while literal
keys won’t be affected.
Parameters
array
116
Chapter 6 Arrays
array_slice
Extracts a slice of the array
array_slice(
array $array,
int $offset,
?int $length = null,
bool $preserve_keys = false
): array
length
If length is given and is positive, the sequence will have up to that
many elements in it.
117
Chapter 6 Arrays
If the array is shorter than the length, only the available array elements
will be present.
If length is given and is negative, the sequence will stop that many
elements from the end of the array.
If it is omitted, the sequence will have everything from offset up until
the end of the array.
preserve_keys
Return values
Returns the slice. If the offset is larger than the size of the array, an
empty array is returned.
array_splice
Removes a portion of the array and replaces it with something else
array_splice(
array &$array,
int $offset,
?int $length = null,
mixed $replacement = []
): array
118
Chapter 6 Arrays
Parameters
array
The input array
offset
If offset is positive, then the start of the removed portion is at that
offset from the beginning of the array array.
If offset is negative, then the start of the removed portion is at that
offset from the end of the array array.
length
If length is omitted, remove everything from offset to the end of
the array.
If length is specified and is positive, that many elements will be
removed.
If length is specified and is negative, the end of the removed portion
will be that many elements from the end of the array.
If length is specified and is 0, no elements will be removed.
replacement
If a replacement array is specified, then the removed elements are
replaced with elements from this array.
If offset and length are such that nothing is removed, the elements
from the replacement array are inserted in the place specified by the offset.
If replacement is just one element, it is not necessary to put array()
or square brackets around it, unless the element is an array itself, an object
or null.
Return values
Returns an array consisting of the extracted elements
119
Chapter 6 Arrays
array_sum
Calculates the sum of values in an array
Parameters
array
The input array
Return values
Returns the sum of values as an integer or float, or 0 if the array
is empty
array_udiff_assoc
Computes the difference of arrays with an additional index check and
compares data by a callback function
Parameters
array
The first array
arrays
Arrays to compare against
value_compare_func
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less
than, equal to, or greater than the second.
Return values
120
Chapter 6 Arrays
array_udiff_uassoc
Computes the difference of arrays with an additional index check and
compares data and indexes by a callback function
array_udiff_uassoc(
array $array,
array ...$arrays,
callable $value_compare_func,
callable $key_compare_func
): array
Note that the keys are used in the comparison, unlike array_diff()
and array_udiff().
Parameters
array
The first array
arrays
Arrays to compare against
value_compare_func
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less
than, equal to, or greater than the second.
key_compare_func
121
Chapter 6 Arrays
array_udiff
Computes the difference of arrays by using a callback function for data
comparison
Return values
Returns an array containing all the values of array that are not present
in any of the other arguments
122
Chapter 6 Arrays
array_uintersect_assoc
Computes the intersection of arrays with an additional index check and
compares data by a callback function
Note that the keys are used in the comparison, unlike in array_
uintersect(). The data is compared by using a callback function.
Parameters
array
The first array
arrays
Arrays to compare against
value_compare_func
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less
than, equal to, or greater than the second.
Return values
Returns an array containing all the values of array that are present in
all the arguments
array_uintersect_uassoc
Computes the intersection of arrays with an additional index check and
compares data and indexes by separate callback functions
array_uintersect_uassoc(
array $array1,
array ...$arrays,
123
Chapter 6 Arrays
callable $value_compare_func,
callable $key_compare_func
): array
Parameters
array1
The first array
arrays
Further arrays
value_compare_func
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less
than, equal to, or greater than the second.
key_compare_func
Key comparison callback function
Return values
Returns an array containing all the values of array1 that are present in
all the arguments
array_uintersect
Computes the intersection of arrays and compares data by a callback
function
Parameters
array
The first array
arrays
124
Chapter 6 Arrays
Return values
Returns an array containing all the values of array that are present in
all the arguments
array_unique
Removes duplicate values from an array
Parameters
array
The input array
flags
125
Chapter 6 Arrays
array_unshift
Prepends one or more elements to the beginning of an array
array_values
Returns all the values of an array and indexes the array numerically
126
Chapter 6 Arrays
Parameters
array
The array
Return values
Returns an indexed array of values
array_walk_recursive
Applies a user function recursively to every member of an array
array_walk
Applies a user-supplied function to every member of an array
127
Chapter 6 Arrays
array
Creates an array
Read the section on the array type for more information on what an
array is.
Parameters
values
128
Chapter 6 Arrays
The syntax “index => values", separated by commas, defines index and
values. index may be of type string or integer. When index is omitted, an
integer index is automatically generated, starting at 0. If index is an integer,
the next generated index will be the biggest integer index + 1. Note that
when two identical indexes are defined, the last overwrite the first.
Having a trailing comma after the last defined array entry, while
unusual, is a valid syntax.
Return values
Returns an array of the parameters. The parameters can be given an
index with the => operator. Read the section on the array type for more
information on what an array is.
arsort
Sorts an array in descending order and maintains index association
129
Chapter 6 Arrays
assort
Sorts an array in ascending order and maintains index association
Sorts array in place in ascending order, such that its keys maintain
their correlation with the values they are associated with. This is used
mainly when sorting associative arrays where the actual element order is
significant.
Parameters
array
The input array
flags
The optional second parameter flags may be used to modify the sorting
behavior using these values:
Sorting type flags:
SORT_REGULAR compares items normally; the details are described in
the comparison operators section.
SORT_NUMERIC compares items numerically.
SORT_STRING compares items as strings.
SORT_LOCALE_STRING compares items as strings, based on the current
locale. It uses the locale, which can be changed using setlocale().
130
Chapter 6 Arrays
compact
Creates array containing variables and their values
For each of these, compact() looks for a variable with that name in the
current symbol table and adds it to the output array such that the variable
name becomes the key and the contents of the variable become the value
for that key. In short, it does the opposite of extract().
Parameters
var_name
var_names
compact() takes a variable number of parameters. Each parameter
can be either a string containing the name of the variable or an array of
variable names. The array can contain other arrays of variable names
inside it; compact() handles it recursively.
Return values
Returns the output array with all the variables added to it
count
Counts all elements in an array or in a Countable object
131
Chapter 6 Arrays
Return values
Returns the number of elements in value. Prior to PHP 8.0.0, if the
parameter was neither an array nor an object that implements the
Countable interface, 1 would be returned, unless the value was null, in
which case 0 would be returned.
current
Returns the current element in an array
132
Chapter 6 Arrays
Return values
The current() function simply returns the value of the array element
that’s currently being pointed to by the internal pointer. It does not move
the pointer in any way. If the internal pointer points beyond the end of the
elements list or the array is empty, current() returns false.
each
Returns the current key and value pair from an array and advances the
array cursor
After each() has executed, the array cursor will be left on the next
element of the array or past the last element if it hits the end of the array.
You have to use reset() if you want to traverse the array again using each.
Parameters
array
The input array
Return values
Returns the current key and value pair from the array array. This
pair is returned in a four-element array, with the keys 0, 1, key, and value.
Elements 0 and key contain the key name of the array element, and 1 and
value contain the data.
If the internal pointer for the array points past the end of the array
contents, each() returns false.
133
Chapter 6 Arrays
end
Sets the internal pointer of an array to its last element and returns its value.
Parameters
array
The array. This array is passed by reference because it is modified
by the function. This means you must pass it a real variable and not a
function returning an array because only actual variables may be passed
by reference.
Return values
Returns the value of the last element or false for empty array
extract
Imports variables into the current symbol table from an array
Checks each key to see whether it has a valid variable name. It also
checks for collisions with existing variables in the symbol table.
Parameters
array
An associative array. This function treats keys as variable names and
values as variable values. For each key/value pair, it will create a variable in
the current symbol table, subject to flags and prefix parameters.
134
Chapter 6 Arrays
You must use an associative array; a numerically indexed array will not
produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.
flags
The way invalid/numeric keys and collisions are treated is determined
by the extraction flags. It can be one of the following values:
EXTR_OVERWRITE
If there is a collision, overwrite the existing variable.
EXTR_SKIP
If there is a collision, don’t overwrite the existing variable.
EXTR_PREFIX_SAME
If there is a collision, prefix the variable name with the prefix.
EXTR_PREFIX_ALL
Prefix all variable names with the prefix.
EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with the prefix.
EXTR_IF_EXISTS
Only overwrite the variable if it already exists in the current symbol
table; otherwise, do nothing. This is useful for defining a list of valid
variables and then extracting only those variables you have defined out of
$_REQUEST, for example.
EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version of the
same variable exists in the current symbol table.
EXTR_REFS
Extracts variables as references. This effectively means that the values
of the imported variables are still referencing the values of the array
parameter. You can use this flag on its own or combine it with any other
flag by OR’ing the flags.
If flags is not specified, it is assumed to be EXTR_OVERWRITE.
prefix
135
Chapter 6 Arrays
in_array
Checks if a value exists in an array
haystack
The array
strict
If the third parameter called strict is set to true, the in_array()
function will also check the types of the needle in the haystack.
Return values
Returns true if needle is found in the array and false otherwise
136
Chapter 6 Arrays
key_exists
Alias of array_key_exists
key
Fetches a key from an array
krsort
Sorts an array by key in descending order
137
Chapter 6 Arrays
ksort
Sorts an array by key in ascending order
Parameters
array
The input array
flags
The optional second parameter named flags may be used to modify
the sorting behavior using these values:
Sorting type flags:
SORT_REGULAR compares items normally; the details are described in
the comparison operators section.
SORT_NUMERIC compares items numerically.
SORT_STRING compares items as strings.
SORT_LOCALE_STRING compares items as strings, based on the current
locale. It uses the locale, which can be changed using setlocale().
138
Chapter 6 Arrays
list
Assigns variables as if they were an array
natcasesort
Sorts an array using a case-insensitive “natural order” algorithm
139
Chapter 6 Arrays
Parameters
array
The input array
Return values
Always returns true
natsort
Sorts an array using a “natural order” algorithm
next
Advances the internal pointer of an array
140
Chapter 6 Arrays
Returns the array value in the next place that’s pointed to by the
internal array pointer or false if there are no more elements.
pos
Alias of current
prev
Rewinds the internal array pointer
prev() behaves just like next(), except it rewinds the internal array
pointer one place instead of advancing it.
Parameters
array
The input array
Return values
Returns the array value in the previous place that’s pointed to by the
internal array pointer, or false if there are no more elements.
141
Chapter 6 Arrays
range
Creates an array containing a range of elements
Parameters
start
First value of the sequence
end
The sequence is ended upon reaching the end value.
step
If a step value is given, it will be used as the increment (or decrement)
between elements in the sequence. step must not equal 0 and must not
exceed the specified range. If not specified, step will default to 1.
Return values
Returns an array of elements from start to end, inclusive
reset
Sets the internal pointer of an array to its first element
142
Chapter 6 Arrays
rsort
Sorts an array in descending order
Parameters
array
The input array
flags
The optional second parameter, flags, may be used to modify the
sorting behavior using these values:
Sorting type flags:
SORT_REGULAR compares items normally; the details are described in
the comparison operators section.
SORT_NUMERIC compares items numerically.
SORT_STRING compares items as strings.
SORT_LOCALE_STRING compares items as strings, based on the current
locale. It uses the locale, which can be changed using setlocale().
SORT_NATURAL compares items as strings using “natural ordering” like
natsort().
SORT_FLAG_CASE can be combined (bitwise OR) with SORT_STRING or
SORT_NATURAL to sort strings case-insensitively.
Return values
Always returns true
143
Chapter 6 Arrays
shuffle
Shuffles an array
sizeof
Alias of count
sort
Sorts an array in place in ascending order
Parameters
array
The input array
flags
The optional second parameter, flags, may be used to modify the
sorting behavior using these values:
Sorting type flags:
SORT_REGULAR compares items normally; the details are described in
the comparison operators section.
144
Chapter 6 Arrays
uasort
Sorts an array with a user-defined comparison function and maintains
index association
Sorts array in place such that its keys maintain their correlation with
the values they are associated with, using a user-defined comparison
function. This is used mainly when sorting associative arrays where the
actual element order is significant.
Parameters
array
The input array
callback
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less
than, equal to, or greater than the second.
Return values
Always returns true
145
Chapter 6 Arrays
uksort
Sorts an array by keys using a user-defined comparison function
Parameters
array
The input array
callback
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less
than, equal to, or greater than the second.
Return values
Always returns true
usort
Sorts an array by values using a user-defined comparison function
Parameters
array
The input array
callback
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less
than, equal to, or greater than the second.
Return values
Always returns true
146
Chapter 6 Arrays
Summary
Overall, arrays can be as simplistic or as complex as you desire. Once you
get comfortable with them, they are a great tool to have in your toolbox.
In this chapter, you learned how to hold multiple values of similar
types in a single variable using PHP arrays, which can be indexed,
associative, and multidimensional. You also learned about the most
common PHP array functions.
In the next chapter, you will learn how to use sessions, which are used
in PHP to keep track of your activity in applications, and cookies, which are
used to store limited data like a user’s identity.
147
CHAPTER 7
Sessions and Cookies
In the previous chapters, you learned how to use arrays, one of the most
versatile and useful elements in PHP, to store multiple values within a
single variable. Let’s now imagine you need to store some information to
be used across multiple web pages. You need to store some information on
a local computer (client side) or store some information on a server (server
side) for just a certain time using the web page. How would you do this? By
using sessions and cookies.
The main difference between sessions and cookies is that cookies,
as previously said, are used to store some user information on a local
computer as client-side files while sessions are server-side files that store
user information on a web server.
While cookies expire right after the specified lifetime you define,
sessions end when you close the web browser or when you log out of the
web page or program.
This chapter consists of the following sections:
• PHP Sessions
• PHP Cookies
PHP Sessions
Sessions are what PHP uses to keep track of your activity on applications.
For example, when you log into an application, make some changes,
upload some images, and then leave the site, that’s a session.
The application knows who you are and has been passing around and
keeping track of a variable ($_SESSION) the whole time. Session variables
hold information about individual users and are passed around the
application to keep track of user activity.
Unlike normal variables, sessions need to be initiated in order to
maintain integrity. To do this, PHP has a session_start() function. After
this, session variables are set with the $_SESSION global variable.
Let’s make a simple page with a basic session declaration. Open the
chapter7 folder and the first_session.php file.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["firstname"] = "Foo";
$_SESSION["username"] = "barFoo";
echo "Session variables are set.";
?>
</body>
</html>
So, session data has been set, but where is it? Sessions are stored on
the server side so you can’t view them through methods such as inspect
element. You can, however, use var_dump() to ensure that they are stored
correctly.
Go browse back to chapter7 and open first_session2.php.
150
Chapter 7 Sessions and Cookies
Great! So now you are saving session variables. For the real test, go back
to chapter7 and find session_test.php. If you can open up a brand new
page and still recall the session data, then you have success. All you need to
do in session_test.php is use the start_session() function to access the
session data. Go ahead and click session_test.php to view the data.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
And for your last trick, let’s view the session variables and then destroy
them! This will remove the session information that is currently active from
the use of session_start().
Click remove_session.php in the chapter7 directory to view and
remove the session data. Here is what remove_session.php looks like:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
151
Chapter 7 Sessions and Cookies
<?php
echo "Here are the variables:<br />";
var_dump($_SESSION);
echo "<br /><br />";
// remove all session variables
session_unset();
echo "Here are the variables after session_unset:<br />";
var_dump($_SESSION);
echo "<br /><br />";
</body>
</html>
Let’s take this concept and put it into a real-life situation, like a login
page connected to a database. http://localhost/chapter7/ will show
you a file called seedDB.php. Go ahead and click it. You will use this file to
seed your database with some information. If all is working properly, you
should see output in your browser that shows
This is the test data you can use for this example. Open up login.php
and take a look at the code.
152
Chapter 7 Sessions and Cookies
<?php
// to Start a PHP session
session_start();
?>
<html>
<body>
<div class="container">
<form method="post" action="">
<div id="div_login">
<h1>Login</h1>
<div>
<input type="text"
class="textbox" id="first_
name" name="first_name"
placeholder="first_name" />
</div>
<div>
<input type="password"
class="textbox"
id="password"
name="password"
placeholder="Password"/>
</div>
<div>
<input type="submit"
value="Submit" name="submit"
id="submit" />
</div>
</div>
</form>
</div>
<?php
153
Chapter 7 Sessions and Cookies
// DB Host name
$host = "mysql-db";
// DB User
$user = "user";
// DB Password
$password = "pass";
// Database name
$db = "beginningPHP";
154
Chapter 7 Sessions and Cookies
}
155
Chapter 7 Sessions and Cookies
}
?>
</body>
</html>
<?php
// to Start a PHP session
session_start();
Here you are using the session_start() function to start your session.
?>
<html>
<body>
<div class="container">
<form method="post" action="">
<div id="div_login">
<h1>Login</h1>
<div>
<input type="text"
class="textbox" id="first_
name" name="first_name"
placeholder="first_name" />
</div>
<div>
<input type="password"
class="textbox"
id="password"
name="password"
placeholder="Password"/>
</div>
156
Chapter 7 Sessions and Cookies
<div>
<input type="submit"
value="Submit" name="submit"
id="submit" />
</div>
</div>
</form>
This is your basic form that you will use to gather the credentials from
your user. Use consistent naming with the database for easier tracking.
This can be anything from “username”/“password” to “user”/“secret.”
</div>
<?php
// DB Host name
$host = "mysql-db";
// DB User
$user = "user";
// DB Password
$password = "pass";
// Database name
$db = "beginningPHP";
This connects to your database using the credentials that will be used
throughout this book. Below, you check for the connection and show an
error if it fails for any reason:
157
Chapter 7 Sessions and Cookies
You need to check the input and sanitize it before introducing it to the
database. This will help prevent MySQL injection attacks.
158
Chapter 7 Sessions and Cookies
}
}
?>
</body>
</html>
Use the test data “tom” and password “1234” to test. You can always go
back to the chapter7 directory and run remove_session.php to clear out
or log out the session data.
Please note that for preventing SQL injection you can use PDO (PHP
data objects), which is an abstraction layer that can be used for database
queries as an alternative to MySQLi.
159
Chapter 7 Sessions and Cookies
PHP Cookies
Cookies are often used to identify a user. A cookie is a small file that is
embedded on the user’s computer by the server. Remember that session
variables are stored on the server, unlike cookies. Each time the same
computer requests a page, the cookie is available for the application to
read and identify the user. PHP can be used to both create and retrieve
these cookie values.
Similar to sessions, you need to make use of a built-in PHP function
named setcookie() to begin using them. The syntax for setting a cookie is
<?php
$cookie_name = "username";
$cookie_value = "Betchy McCleaver";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30),
"/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
160
Chapter 7 Sessions and Cookies
161
Chapter 7 Sessions and Cookies
<?php
// set the expiration date to one hour ago
setcookie("username", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
162
Chapter 7 Sessions and Cookies
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Here you attempt to set an arbitrary cookie and then read it. If you can
verify that the cookie is set, you know the user has cookies enabled!
Summary
In this chapter, you learned how to use sessions and cookies in the PHP
language to keep track of your activity on web applications. You saw how to
create, store, and manage information in PHP sessions and cookies.
In the next chapter, you will learn how to use PHP objects, which are
another compound data type. They are similar to arrays, which can be set
and used with multiple types of information, from strings to all types of
numbers.
163
CHAPTER 8
Objects
So far, we have covered several data types, including the string, integer, and
float. You’ve learned how to use strings, integers, and arrays. Each of these
types has their own benefits and limitations. An integer cannot use the
letter “s” as a value, and a string can contain an integer of “1.” With arrays,
you learned about the idea of a compound data type. This data type allows
for combining and intermixing of different elements. An array can contain
both letters and numbers, contain specific key-pair values (associative
array), or just contain an organized set of data. The end result is that values
of more than one type can be stored together in a single variable.
In this brief chapter, we will focus on a PHP data type we touched on in
Chapters 2 and 4: the object.
Please notice that, in general, classes and objects are the two main
aspects of object-oriented programming and are therefore very important.
To understand how classes and objects are interlinked, we could say that a
class is a template for an object and an object is an instance of a certain class.
Similar to arrays, you can set and use multiple types of information,
from strings to all types of numbers. Objects, however, give you the ability to
define specific functionality. This functionality is set in the class definition.
So, when you create an individual object, it will inherit all the
properties and behaviors from the class it’s linked to, but each object will
still have different values for the properties.
Objects are user-defined classes that can store both values and
functions and must be explicitly declared.
Let’s take a look at some basic examples.
<?php
class Vegetable {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Here you are declaring a class named Vegetable. This class contains
both properties and methods. Remember that properties are variables
and methods are functions. The two properties are $name and $color. The
two methods are set_name and get_name. They are commonly referred to
as “getters and setters.” These types of methods are common with objects
because you are constantly “getting” and “setting” values to the class
properties. It is very convenient to create these helper type functions. If
you have these functions in your objects, you will only need to remember
to $vegetable->get_name(); and $vegetable->set_name();.
Here is another example of an object:
<?php
class SayHi{
function hi(){
echo "Hello World";
}
}
166
Chapter 8 Objects
$obj=new SayHi;
$obj->hi();
?>
<?php
$obj=new stdClass;
$obj->name="gunnard";
$obj->age=26;
$obj->twitter="@gunnard";
print_r($obj);
?>
Output
This will produce following result:
stdClass Object(
[name] => gunnard
[age] => 26
[twitter] => @gunnard
)
Let’s start fresh with a basic class and see how changes in the class
affect the object. You will create a Beverage class to classify and track
information on beverages at the pizzeria that you run.
167
Chapter 8 Objects
<?php
class Beverage {
public $name;
public $type;
public $temperature;
public $price;
public $sale;
}
In order to use this class as an object, you need to instantiate it. This is
done through the new keyword.
<?php
$cola = new Beverage();
?>
Now you have an object with the name $cola, which contains the
properties you defined in the class Beverage. You can use this object by
assigning values to the properties with the -> operator. This will allow you
to assign specific values to each property.
<?php
$cola = new Beverage();
$cola->name = "Rocky Cola";
$cola->type = "Soda";
$cola->teperature = "45 f";
$cola->price = "0.50";
$cola->sale = null;
?>
Now that you can set values to your class properties, let’s add class
methods or functions within a class that allow objects to manipulate data.
For example,
168
Chapter 8 Objects
<?php
class Beverage {
public $name;
public $type;
public $temperature;
public $price;
public $sale;
}
function getMenuName() {
return $this->type:.' '.$this->name.' '.$this->price;
}
?>
With getMenuName, the intention is to display the type, name, and price
of the beverage. This can be used when displaying the full menu of the
restaurant. Instead of using the object to return the name, type, and price,
and THEN formatting it, you can take care of all of that in this method.
The $this variable refers to the current object in use. When you invoke
the getMenuName() method, $this refers to the specific object that calls
the method. Object methods are accessed similarly to properties, using the
object operator ->, but as with any function, there are parentheses at the
end, as in ().
Summary
In this chapter, you learned how to use a PHP object, which is another
compound data type. It is similar to an array, which can be set and use
with multiple types of information, from strings to all types of numbers.
In the next chapter, you will learn how …
169
CHAPTER 9
PHP Exceptions,
Validation,
and Regular
Expressions
PHP is indeed one of the most used programming languages in the world
to develop applications and websites on the Internet. PHP 8 is a very
dynamic, flexible programming language; it’s also easy to use as embedded
language, for instance, for HTML.
In this chapter, you will learn all about exceptions, form validation, and
regular expressions. What are they and when do we need to use them?
PHP is indeed very flexibility programming language, also when it
comes to handling exceptions, which are out-of-the-ordinary scenarios
that may occur in code. A code exception can be something like an input
or code bug, and PHP version 8, compared to previous versions, has been
updated to be more secure and to handle more exceptions better.
We will explain how to use PHP exceptions using try, catch,
and throw.
Also, as developer, you will need to do web form validation, which
means validating certain values entered in a PHP form of various input
field types like text boxes, checkboxes, radio buttons, and checklists.
PHP Exceptions
As we said in the introduction of the chapter, an exception in a
programming language is simply an unexpected outcome of a PHP
program. Your goal is to tell your code how to handle any unexpected
outcome by itself, where possible.
Please remember that the main difference between an error and an
exception is that an exception will disrupt the normal flow of your code but
by adding some additional code it can be handled while an error cannot
be handled by the code itself. You will see how to use PHP to handle
exceptions thrown and catch them.
PHP, like all programming languages, must have a code exception
mechanism to handle runtime errors, also known exceptions. This, in PHP
and any other language, is necessary to maintain the normal flow of the
application.
Each language includes a set of throwable exceptions and errors. In
PHP, there are many different types of errors that may occur in your code.
Here are some:
172
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
• CompileError
• ParseError
• TypeError
• ArithmeticError
Chapter9/exception1.php
173
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
<?php
//here we create a function with an exception
function checkMyNum($mynumber) {
if($mynumber>1) {
throw new Exception("The entered number must be 1 or
below!!");
}
return true;
}
checkMyNum(3);
?>
To fix this error, let’s see how to handle and correct the above uncaught
exception error by using PHP exception handling ways named try, catch,
and throw.
174
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
<?php
try {
// do something in our code
} catch (Exception $e) {
// code to handle any exception
} finally {
// code to clean up the resource and complete the code
execution
}
In general, this is what happens when you run the code and an
exception is triggered:
175
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
Let’s now take your uncaught exception error PHP code and fix it with
try, catch, finally, and throw methods.
Chapter9/exception2.php
<?php
//here we create a function with an exception
function checkMyNum($mynumber) {
if($mynumber>1) {
throw new Exception("The entered number must be 1 or
below!!");
}
return true;
}
?>
176
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
177
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
Chapter9/form-action.html
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>PHP Form Validation</h2>
<form method="post" action="form-action.php" >
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When you run your HTML form, it will look like Figure 9-1.
178
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
Now you need to write some PHP code that will allow you to simply verify
the values entered as Name and E-mail before they are sent to the server.
Suppose you wish to have the HTML value of Name required and that
it must only contain letters and whitespace. The E-mail value will also
be required and must contain a valid email address (including @ and . as
typical email format characters).
Let’s start from the previous HTML web page and add some PHP
validation code. Create a new PHP file named form-action.php, which for
now will only validate if the values entered are not empty:
Chapter9/form-action.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$name = "";
$email = "";
$nameError = "";
$emailError = "";
if (empty($_POST["name"])) {
$nameError = "Name is required";
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
}
?>
179
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
</body>
</html>
When you run your PHP file, it will look like Figure 9-2.
As you can see, the web form informs you that the Name and E-mail
fields are required and therefore cannot be empty. When you try to submit
the form with one or both fields empty, you will get the error messages
shown in Figure 9-3.
180
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
Figure 9-3. PHP form web page submitted with empty fields
Let’s update the PHP example so that it will validate the value entered for
Name, which must only be letters and whitespace, and validate that the format of
the E-mail value must contain @ and . characters as part of the value submitted.
Here is the updated code:
Chapter9/form-action.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$name = "";
$nameError = "";
$email = "";
$emailError = "";
if (empty($_POST["name"])) {
$nameError = "Name is required";
181
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameError = "Error: Only letters and whitespace
allowed!";
}
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Error: Invalid email format!";
}
}
?>
</body>
</html>
182
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
Rerun your PHP file. Now, just entering some special characters in the
Name field and entering the E-mail value with no @ or . characters will
result in error messages that the characters are not allowed and the email
format is invalid. See Figure 9-4.
Figure 9-4. PHP form web page submitted with invalid values
When you analyze the code, you see that to validate the Name value,
you utilize the PHP regular expression function preg_match() (you will
learn more about it later in this chapter), which returns 1 if the pattern is
found in the string and 0 if it is not.
So, in your PHP code you define the function as preg_match("/^[a-
zA-Z-' ]*$/",$name)), where you force the value entered to have only
letters and whitespace. If not, the code will produce an error message of
“Error: Only letters and whitespace allowed!”
To validate the E-mail value, you use the PHP function named filter_
var(), which filters a variable with a specified filter and utilizes the PHP
predefined filter constant FILTER_VALIDATE_EMAIL, which validates a value
as a valid format for an entered e-mail address.
If you didn’t enter @ or ., the code will produce the error “Error: Invalid
email format!”
Let’s now learn how to use PHP regular expressions.
183
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
$pattern = "/mas[si]mo/i";
$text = "My name is Massimo.";
where
• / is the delimiter .
184
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
• @Text is the given string you will search the pattern in.
185
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
186
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
187
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
Let’s start your first example of PHP regular expression using preg_
match(), which will return 1 if the pattern is found in the string and 0 if it is
not. Here is the code:
Chapter 9 (regexpress1.php)
<?php
$pattern = "/massimo/i";
$text = "My name is Massimo.";
if(preg_match($pattern, $text)){
echo "Match was found!"; }
else{
echo "Match was not found."; }
?>
<?php
$pattern = "/mas[trgs]imo/i";
$text = "My name is Massimo.";
if(preg_match($pattern, $text)){
echo "Match was found!"; }
else{
echo "Match was not found."; }
?>
188
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
Chapter9/regexpress3.php
<?php
$pattern = "/imo$/";
$text = "Massimo";
if(preg_match($pattern, $text)){
echo "Match was found!"; }
else{
echo "Match was not found."; }
?>
The output of this code is Match was found! as the pattern “imo” is
found at the end of the text “Massimo.”
Let’s create an example of a regular expression with a group and
quantifier. You want to search for a match in a string that contains the
letters “co” exactly two times.
Chapter9/regexpress4.php
<?php
$pattern = "/(co){2}/i";
$text = "I like coconut.";
if(preg_match($pattern, $text)){
echo "Match was found!"; }
else{
echo "Match was not found."; }
?>
189
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
The output of this code is Match was found! because the pattern “co”
is found exactly two times in the text “I love coconut.”
Let’s create a new PHP example of a regular expression using preg_
match_all(), which will return the number of how many times the pattern
was found in the string.
Chapter9/regexpress5.php
<?php
$pattern = "/na/i";
$text = "My name is Massimo and I was born in Naples";
echo preg_match_all($pattern, $text);
?>
The output of this code is 2 because the pattern “na” is found two
times: in the words “name” and “Naples,” because you added I so the case
is insensitive.
Finally, let’s create a new PHP example of a regular expression using
preg_replace(), which returns a very new string where matched patterns
are replaced with another string.
Chapter9/regexpress6.php
<?php
$pattern = "/red/i";
$text = "My favorite color is red!";
echo preg_replace($pattern, "blue", $text);
?>
The output of this code is “My favorite color is blue!” because the
pattern “red” is found in the text and is replaced with the new text “blue.”
The case is insensitive because you added i.
190
Chapter 9 PHP Exceptions, Validation, and Regular Expressions
Summary
In this chapter, you first learned about PHP proper exceptions and how
to deal with them using the try, throw, and catch methods. Then you
saw how to use PHP to validate client HTML form values entered before
sending the value to the server. Finally, you learned about PHP regular
expressions, which are used almost everywhere in current application
programming, allowing you to search for a specific pattern of characters
inside a given string.
In the next chapter, you will see PHP and MySQL working together and
learn how to create MySQL databases, tables, and use PHP programming
code to handle them.
191
CHAPTER 10
PHP and MySQL
Working Together
As you have seen so far, PHP is very capable and easy to manipulate and
use to display data. Where does this data come from? There are two types
of data that PHP can use: static and dynamic. We can think of static data
as non-changing and dynamic as able-to-be-changed. This dynamic data
is stored in a database. Simply put, a database is a structured organization
of data. Think of a folder of spreadsheets. The key to databases, however,
is that we can easily search or query a database based on how we have set
up our structure. These queries can be as basic as “show me all the users’
first names” to “show me all the first names of users who registered on a
Tuesday after 2 p.m.” The query complexity comes from the SQL in MySQL
(Structured Query Language). This language, once understood, can be
used with a Mad Libs approach in PHP. We can simply replace certain
words and phrases with PHP variables in order to dynamically influence
the result of the query.
In this chapter, we will start with the basics, of course, and simply get
PHP to communicate with MySQL.
This chapter consists of the following sections:
• MySQLi Advantages
On the top line is an IMAGE for mysql:8.0 and on the very right side is
the name mysql-db. In order for PHP to use MySQL, you need to connect
to it first. PHP comes with two different methods: through the MySQLi and
PDO APIs. Below are code examples of each method.
</code>
194
Chapter 10 PHP and MySQL Working Together
Without getting into detail, right now at least, in the context of these
examples, let’s at least break them down and see what you are doing
and why.
In this first MySQLi example, there should be some standout items that
are recognizable on first read.
<code>
$mysqli = new mysqli("db.mysite.com", "user", "password",
"database");
</code>
You have $mysqli, which is a PHP variable being set to new mysqli
with some parameters. You can gather from this that mysqli is a class and
$mysqli will become an object once created. Let’s see if you can determine
what the parameters of the class constructor are without Googling for an
answer. The first parameter is “db.mysite.com”. The db in the subdomain
stands for database so a logical guess would be that this first parameter
is the database server. The next ones are straightforward: “user” is the
username and “password” is the password for the user you are connecting
with through PHP. The final parameter of “database” is, well... the name of
the database. These four parameters are needed in order to create a valid
MySQLi connection. They can be directly input, as in this example, or you
can use variables such as $dbServer, $dbUser, $dbPass, and $dbName
and store them in a separate file for your own organization. This will often
be the case in PHP applications.
The next line is
This sets $result equal to the result of the query method of the
$mysqli object. You see this in the form of the syntax $mysqli->query. The
properties that are passed make up the actual query you would like to send
to MySQL. More on these queries later.
195
Chapter 10 PHP and MySQL Working Together
$row = $result->fetch_assoc();
This sets the variable $row to the value of the object $result after
the fetch_assoc() method is run. After the query, you can receive your
results all at once or row by row from the server. To save resources on your
server, you want all of the data at one time. This will allow you to use PHP
to consume and parse the data however you please without bothering the
database server more than you need to. The method fetch_assoc() is in a
group of available methods for MySQL. These methods are
$row['firstname'] Vs $row[0]
echo $row['_message'];
196
Chapter 10 PHP and MySQL Working Together
Here you use echo to show the results of the PHP function
htmlentities on the variable $row, specifically the data in the ['_
message'] id of the array. This is the specific data you are querying for.
<code>
<?php
// PDO
$pdo = new PDO('mysql:host=localhost;dbname=myDatabase, 'user',
'password');
$statement = $pdo->query("SELECT 'message' AS theMessage FROM
'messages'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo $row['theMessage'];
</code>
Here you create a new object named $pdo from the class PDO with a
similar structure for passing the database host, database name, username,
and password to the constructor.
The next line is
Here you set the $statement in a similar way to the $pdo object
method query.
197
Chapter 10 PHP and MySQL Working Together
echo $row['_message'];
MySQLi Advantages
• Asynchronous queries
PDO Advantages
• Useful fetch modes
198
Chapter 10 PHP and MySQL Working Together
• Named parameters
<code>
<?php
require_once('db.php');
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_
DATABASE);
</code>
199
Chapter 10 PHP and MySQL Working Together
Line 4 is the $mysqli = new mysqli line. This looks correct to me, so
there must be an issue with the variables used in the mysqli constructor.
As you see on line 3, you are reading these variables from db.php. Let’s
open that file.
<code>
<?php
$DB_HOST = '';
$DB_USER = 'root';
$DB_PASS = 'pass';
$DB_DATABASE = 'beginningPHP';
</code>
Ahh! Look at that! In line 2, $DB_HOST is set to ‘‘and not an actual host. If
you remember, your host is set to db. Let’s go ahead and replace the empty
space with db.
<code>
<?php
$DB_HOST = 'db';
$DB_USER = 'root';
$DB_PASS = 'pass';
$DB_DATABASE = 'beginningPHP';
</code>
<code>
Creating table "USERS"Seeing Users into table..1..2..3
Users added
1 - tom - hanks - 2021-06-25 17:58:42
2 - billy - mitchell - 2021-06-25 17:58:42
200
Chapter 10 PHP and MySQL Working Together
<code>
<?php
require_once('db.php');
$result = $mysqli->query($query);
if ($result) {
echo '<h1>Users in Database</h1>';
while ($row = $result->fetch_assoc()) {
echo "Name: {$row['first_name']} {$row['last_name']} =
Created: {$row['created']} </br>";
201
Chapter 10 PHP and MySQL Working Together
}
} else {
echo "No Results. Have you run <a href='http://localhost/
chapter4/seedDB.php'>SeedDB</a>?";
}
</code>
<code>
<?php
require_once('db.php');
</code>
This is the standard beginning of a PHP file. You first require the db.
php file to be loaded. Remember, this sets the variables for your database
host, user, password, and database name.
<code>
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_
DATABASE);
$query = "SELECT * FROM users";
</code>
<code>
$result = $mysqli->query($query);
</code>
Here you use the object $mysqli and its method query to submit your
query to the database. The result will be set as the variable $result.
<code>
if ($result) {
echo '<h1>Users in Database</h1>';
while ($row = $result->fetch_assoc()) {
202
Chapter 10 PHP and MySQL Working Together
This code may look complex but you are doing some pretty basic
(for humans) logic. In programming languages, this type of “obvious to
humans” logic takes precise logic handling in order to make sure that you
account for all situations and stay away from errors. The if ($result) is
PHP checking if $result evaluates to any “truthy” value. This can be
• Boolean TRUE
• Non-empty value
• Non-NULL value
• Non-zero number
You are basically asking if any useful data was found and returned to
you. You will handle the scenario of nothing being returned a few lines
down. First, let’s deal with the data you do have.
<code>
echo '<h1>Users in Database</h1>';
while ($row = $result->fetch_assoc()) {
echo "Name: {$row['first_name']} {$row['last_name']} =
Created: {$row['created']} </br>";
}
</code>
203
Chapter 10 PHP and MySQL Working Together
Here you echo out a header for the page using the HTML <h1> tags.
Then you begin a while loop, which in PHP loop from beginning to end
until a specified condition is meet. You can think of this like “while the
traffic light is green, keep driving” or “while the pasta is not cooked, keep
cooking.” Once either of those two conditions change (the traffic light
becomes red or the pasta is cooked), the loop will stop. In your code, you
are saying “while $row is equal to data fetched from the database as an
associative array, run the loop.” Your loop is simple and it echoes your
results from the database one row at a time. Once $row does not equal
data from the database or the database is finished returning data, this loop
will stop.
<code>
} else {
echo "No Results. Have you run <a href='http://localhost/
chapter4/seedDB.php'>SeedDB</a>?";
}
</code>
204
Chapter 10 PHP and MySQL Working Together
queries you can do in MySQL. Let’s modify this a bit. What if you want to
retrieve the list of names in alphabetical order by last name? Modify the
query and run this:
<code>
$query = "SELECT * FROM users ORDER by last_name ASC"
</code>
<code>
Users in Database
Name: tom hanks = Created: 2021-06-28 14:17:45
Name: mega man = Created: 2021-06-28 14:17:45
Name: billy mitchell = Created: 2021-06-28 14:17:45
</code>
Another useful modifier for this query is LIMIT. Let’s say, for example,
there are thousands of users in this database but you only want the top
three ordered by score. This query would look like the following (also
found in showUSers3.php):
205
Chapter 10 PHP and MySQL Working Together
<code>
$query = "SELECT * FROM users ORDER by score DESC LIMIT 3";
</code>
So far you have read from the database through the SELECT query.
The purpose of using a database in the backend of your website is for data
to both read and store data. This is how photos show up on Instagram
and how tweets enter the twitterverse. A user can take their tweet (data)
and send it to the database where it gets stored in a table with specific
values assigned to the associated columns. Let’s add another user to
your database and you will see how this works. You will use PHP MySQL
prepared statements. The advantage to using prepared statements is
twofold:
<code>
<?php
require_once('db.php');
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_
DATABASE);
206
Chapter 10 PHP and MySQL Working Together
$firstName = "Freddy";
$lastName = "Krueger";
$age = 40;
$score = 301;
$query->execute();
$mysqli->close();
</code>
The first few lines should look familiar at this point. This is where you
introduce the database variables stored in db.php and create an object
named $mysqli from the mysqli class.
<code>
$query = $mysqli->prepare("INSERT INTO users (first_name, last_
name, age, score) values (?,?,?,?)");
</code>
This line looks familiar but very different. This is your INSERT query,
which you are creating for use as a prepared statement.
<code>
$query = $mysqli->prepare
</code>
Here you create a variable named $query, which is the result of the
method prepare from the object $mysqli. prepare takes the query you
want to run in MySQL but gives you the ability to bind parameters to
minimize bandwidth on the server, as you only send the parameters each
time and not the whole query. The query uses the verb INSERT, which has
a structure of
<code>
INSERT INTO <table> (column1, column2, column3, ...) VALUES
(Value1, value2, value3, ...);
</code>
207
Chapter 10 PHP and MySQL Working Together
You use the column structure of the users table to insert values for
first_name, last_name, age, and score. But where are the values? There
are only question marks (?s). This is the binding element. MySQL looks at
these question marks and sets that space aside for the specified amount of
values to be assigned later; in your code, it is on the next line.
<code>
$query->bind_param("ssii",$firstName, $lastName, $age, $score);
</code>
This code uses the $query object you created earlier and this time you
use the bind_param method, which takes in two sets of parameters. The
first (“ssii”) in your example is the list of the types of parameters that you
are binding. You are using “ssii”, which stands for “string, string, integer,
integer” or first_name, last_name, age, score. MySQL accepts
four types:
Now that you have told MySQL what types of variables to expect, you
list the variables you will be using.
<code>
$firstName = "Freddy";
$lastName = "Krueger";
$age = 40;
$score = 301;
</code>
208
Chapter 10 PHP and MySQL Working Together
Now you assign values to the variables you have already told MySQL
you will be using for the query: two strings and two integers, just like you
declared using “ssii”.
<code>
$query->execute();
$mysqli->close();
</code>
Lastly, you execute the query by calling the method execute from the
$query object and then you close the connection to MySQL.
Go to http://localhost/chapter4/addUser.php and then back to
http://localhost/chapter4/showUser.php to see the results. You should
see one additional user in the table. If you refresh addUser multiple times,
you will get multiple additions to the table. Now that you have some basic
techniques for interacting with MySQL, in the next chapter you will take
a deeper dive into more complex queries, data organization, and MySQL
features.
Summary
In this chapter, you learned the basics of working with PHP and
MySQL. You first learned how to connect to the DB using two methods
such as MySQLi and PDO. You learned the advantages of using one
method or the other. Finally, you explored the code needed to connect to
the DB and show the users included in it.
In the next chapter, you will learn more about the data types you can
utilize in the MySQL DB table, like CHAR and VARCHAR, and how to
define multiple dependencies in queries.
209
CHAPTER 11
Data
So far, you have used MySQL to store a simple user table with a few
columns. This was good for some quick examples, but what about more
complex queries that have multiple dependencies?
In this chapter, let’s chart out some data that you can use for a camp
registration/management database.
This chapter consists of the following sections.
212
Chapter 11 Data
The first example makes use of the index, which results in a faster
response time.
Do not use
213
Chapter 11 Data
This is a basic design for a database that a camp would use in order
to keep track of their campers, camp sites, and registrations. In order to
use this properly for your project, you need to set up and create these
tables, seed them with data, and use PHP to manage them through
214
Chapter 11 Data
<code>
docker ps
</code>
docker ps
CONTAINER ID IMAGE COMMAND
CREATED STATUS
PORTS NAMES
d5d98b7de503 beginning-php8-and-mysql_app "docker-php-entrypoi…"
2 days ago Up 2 days
9000/tcp php-app
63715c3c4f52 nginx:alpine "/docker-entrypoint.…"
2 days ago Up 2 days
0.0.0.0:80->80/tcp, :::80->80/tcp php-nginx
21f2a4b87b7b mysql:8.0 "docker-entrypoint.s…"
2 days ago Up 2 days
0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp mysql-db
You can see that your MySQL container is named mysql-db and with
Docker you can now connect to that container just like you would to
a server.
215
Chapter 11 Data
<code>
docker exec -ti mysql-db bash
</code>
This command tells Docker that you would like to execute a command
named -ti to create a pseudo TTYl. This basically allows you to use
your terminal to be the interface to this container while the i stands
for interactive mode, meaning you want to use this container like a live
system. The next attribute is mysql-db, which is the name of the container
you are connecting to, and finally you want to run bash. Bash is a shell for
Unix/Linux systems that allows you access to the filesystem and to run
scripts. Once you press Enter, you will be “inside” the My SQL container.
Once connected, you need to run the following:
<code>
mysql -uroot -ppass
</code>
This connects you to MySQL using the username root and password
pass. This is typically not encouraged, but in closed networking situations
and development environments you can allow for such casualness.
The first thing you need to know and do once connected to MySQL is
list the databases.
<code>
show databases;
</code>
Note that all MySQL commands end with a semicolon. If you type a
command and press Enter without the semicolon, it will just move down to
the next line and wait for you to type more or to type a semicolon. You can
just type a semicolon and then Enter to continue with your command.
In this list, you should see beginningPHP. Type
216
Chapter 11 Data
<code>
use beginningPHP;
</code>
Now type
<code>
show tables;
</code>
This command, well, shows the tables available in the current database
you are using. There should be a users table. This is fine and you will just
set it aside for now. Let's begin creating the tables for your camping data.
In the chapter5 directory there is a file called campers.sql.
<code>
create table IF NOT EXISTS campers(
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(40) NOT NULL,
age INT NOT NULL,
campId INT default 0,
created DATETIME NOT NULL ON UPDATE CURRENT_
TIMESTAMP default current_timestamp,
PRIMARY KEY ( id )
);
</code>
Take this code and paste it into the MySQL command line and press
Enter. Now type show tables; again.
217
Chapter 11 Data
<code>
mysql> show tables;
+------------------------+
| Tables_in_beginningPHP |
+------------------------+
| campers |
| users |
+------------------------+
2 rows in set (0.00 sec)
</code>
You now have a campers table in the database. To see the structure of a
table, type
<code>
desc campers;
</code>
Desc is for Describe and it will show you the layout for the table. Now
let’s create the table to hold the information for your camps. Look inside
camps.sql in the chapter5 directory.
<code>
create table IF NOT EXISTS camps(
id INT NOT NULL AUTO_INCREMENT,
camp_name VARCHAR(100) NOT NULL,
size INT NOT NULL,
created DATETIME NOT NULL ON UPDATE CURRENT_
TIMESTAMP default current_timestamp,
PRIMARY KEY ( id )
);
</code>
218
Chapter 11 Data
Copy and paste this code into the MySQL command line and
press Enter.
Now type show tables; and see the results:
<code>
show tables;
+------------------------+
| Tables_in_beginningPHP |
+------------------------+
| campers |
| camps |
+------------------------+
2 rows in set (0.03 sec)
</code>
Lastly, let’s create a table for the registered campers. Repeat the steps
from above with registered.sql.
Open registered.sql. Copy and paste the code into the MySQL
command line and press Enter.
Type show tables; and see the results.
Now that you have your data, let’s see next how you can use relational
queries to create simple and complex queries for your app.
Summary
In this chapter, you learned which data types you can utilize in a
MySQL DB table, like CHAR or VARCHAR, and how to define multiple
dependencies in queries.
In the next chapter, you will combine everything you have learned into
one example website to create, read, update, and delete data (otherwise
known as CRUD). You will learn how a basic CRUD website can be a
standard way to manage information within a business or organization.
219
CHAPTER 12
Website with a DB
In this chapter, you will be combining everything you have learned into one
example website. This website will allow you to create, read, update, and
delete (otherwise known as CRUD). A basic CRUD website is a standard way to
manage information within a business or organization. Almost every application
out there can be broken down into CRUD if you think about it. Facebook
allows you to create posts, read posts, update them or your profile, and delete
information. This functionality is the basic interaction that most websites are
looking for, but your imagination is the limit to where you can go with it.
This chapter will cover the following:
For this example, you will create the basic CRUD for you to review and
add to. This CRUD uses both POST and GET methods as well as MySQL PDO
parameter binding. This is a great first step towards developing a more
dynamic and advanced application.
Let’s get right into this with home.php within the chapter12 link.
<?php
$title = "Home";
$thisDir = 12;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="../bootstrap/css/bootstrap.min.css"
rel="stylesheet">
</head>
<div class="container">
<header class="d-flex flex-wrap justify-content-center
py-3 mb-4 border-bottom">
<a href="/" class="d-flex align-items-center mb-3 mb-
md-0 me-md-auto text-dark text-decoration-none">
<svg class="bi me-2" width="40" height="32"><use
xlink:href="#bootstrap"></use></svg>
<span class="fs-4"><?= $title ?></span>
</a>
</div>
This section creates the header and navigation for the app. For now,
these links are static, but they can be made dynamic through reading
menu items from a database, for example.
222
Chapter 12 Website with a DB
<?php
try {
echo '<br />';
echo 'Current PHP version: ' . phpversion();
echo '<br />';
$host = 'mysql-db';
$dbname = 'beginningPHP';
$user = 'user';
$pass = 'pass';
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8";
$conn = new PDO($dsn, $user, $pass);
function deleteBook($theBook) {
global $conn;
$sql = "delete FROM `books` WHERE `id`=$theBook";
$result = $conn->query($sql);
echo "Book Deleted<br />";
}
223
Chapter 12 Website with a DB
function showEditBook($theBook) {
global $conn;
$sql = "SELECT * FROM `books` WHERE `id`=$theBook";
$result = $conn->query($sql);
foreach($result as $row) {
$addForm ='<form action="home.php"
method="post"><table>';
$addForm .= '<tr><td>Title</td><td><input type="text"
name="title" value="'.$row['title'].'"></td></tr>';
$addForm .= '<tr><td>Author</td><td><input type="text"
name="author" value="'.$row['author'].'"></td></tr>';
$addForm .= '<tr><td>Category</
td><td><input type="text" name="category"
value="'.$row['category'].'"></td></tr>';
$addForm .= '<tr><td>ISBN</td><td><input type="text"
name="isbn" value="'.$row['isbn'].'"></td></tr>';
$addForm .= '<tr><td></td><td><input type="submit"
name="submit"></td></tr>';
224
Chapter 12 Website with a DB
The function showEditBook shows the edit book form given the book
id ($theBook). With this form, you then submit it back to home.php via
POST. With this form, you can add validation to ensure that values are
properly filled out and able to be added into the database. The hidden
field is there as an indicator to home.php as to how to handle the form
submission. You will get to that later when you update the book in a
function.
function showAddBook() {
$addForm ='<form action="home.php" method="post"><table>';
$addForm .= '<tr><td>Title</td><td><input type="text"
name="title"></td></tr>';
$addForm .= '<tr><td>Author</td><td><input type="text"
name="author"></td></tr>';
$addForm .= '<tr><td>Category</td><td><input type="text"
name="category"></td></tr>';
$addForm .= '<tr><td>ISBN</td><td><input type="text"
name="isbn"></td></tr>';
$addForm .= '<tr><td></td><td><input type="submit"
name="submit"></td></tr>';
$addForm .= '<input type="hidden" name="bookToAdd"
value="true">';
$addForm .= '</table></form>';
echo $addForm;
}
225
Chapter 12 Website with a DB
The function showAddBook shows the Add a book form. Again, here you
use a hidden field to notify home.php via POST what action you want to take.
function showBooks() {
global $conn;
$sql = "SELECT * FROM `books` WHERE `id`";
$result = $conn->query($sql);
if ($result !== false) {
$rowCount = $result->rowCount();
echo "Number of Books: $rowCount <br />";
}
foreach($result as $row) {
echo $row['id'].' - '. $row['title'] .' - '.
$row['author'] .' - '. $row['category'] .' - '.
$row['isbn'] .' [ <a href="home.php?q=edit&book='.$row
['id'].'"> Edit</a> <a href="home.php?q=delete&book='.$
row['id'].'"> Delete</a> ]<br />';
}
}
The function showBooks is the default display of the page. It shows all
of the books in the database with links to edit and delete.
if (isset($_GET['q'])) {
if ($_GET['q'] == 'add') {
echo "Adding Book<br />";
showAddBook();
}
if ($_GET['q'] == 'edit') {
$theBook = $_GET['book'];
echo "Editing Book<br />";
showEditBook($theBook);
}
226
Chapter 12 Website with a DB
Above is the logic that you use to determine what action to take via
GET. Remember that GET variables are the ones used within the URL. You
use q as the variable you assign to the action (add, edit, delete) in
your URL.
if (isset($_POST['bookToUpdate'])) {
global $conn;
$sql = "update books set title=?, author=?, category=?,
isbn=? where id=?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bindParam(1,$_POST['title']);
$stmt->bindParam(2,$_POST['author']);
$stmt->bindParam(3,$_POST['category']);
$stmt->bindParam(4,$_POST['isbn']);
$stmt->bindParam(5,$_POST['bookToUpdate']);
if($stmt->execute()) {
echo "Book ". $_POST['title'] ."added";
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo "</br>Stmt error: ".$stmt->error();
}
}
The above if statement checks to see if you are calling for the variable
bookToUpdate. If this variable is set, then you attempt to update a book.
227
Chapter 12 Website with a DB
if (isset($_POST['bookToAdd'])) {
global $conn;
$sql = "insert into books (title, author, category, isbn)
VALUES (?,?,?,?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bindParam(1,$_POST['title']);
$stmt->bindParam(2,$_POST['author']);
$stmt->bindParam(3,$_POST['category']);
$stmt->bindParam(4,$_POST['isbn']);
if($stmt->execute()) {
echo "New Book added";
}
}
}
showBooks();
228
Chapter 12 Website with a DB
This is the default view for this page, a list of books available:
?>
</div>
With the improvements listed above, try turning this into an API that
returns JSON data. Instead of returning HTML, the output should look
something like this pseudo-code:
Summary
In this chapter, you combined everything you have learned so far and build
one example website. You learned how to build this website to create, read,
update, and delete (otherwise known as CRUD) and use it with both POST
and GET methods as well as the MySQL PDO parameter binding.
In the next chapter, you will learn about frameworks, which use a lot of
best practices and design patterns so as to allow developers to quickly use
them to solve problems.
229
CHAPTER 13
Introduction
to Frameworks
After having learned in the previous chapters how to build a website, in
this chapter you will focus on programming development frameworks. You
will learn what they are and when to use them.
This chapter consists of the following sections:
• Introduction to Frameworks
• Pros and Cons of Frameworks
• MVC Pattern
• Different Layers of a Framework
• Different Types of Frameworks
• Introduction of PHP Standard Recommendation (PSR)
• PHP Frameworks
Introduction to Frameworks
Until now, you have built the different layers of an application: the UI
components to parse values and display the view pages, connect to the
database and fetch data, authenticate use, and maintain sessions. If you
observe, these contextual areas are reusable structures and elements that
are used in every project or application based on different use cases.
They have structural value but do not add value in terms of helping
developers and teams develop new features and business logic.
Recognizing the recurrence of these common structural elements, many
smart people felt that they could be developed and packaged together
so that these structures could interface with each other and be reused.
In essence, they created a framework, which is a supporting structure
that helps you get started developing your applications, thus delivering
business value, instead of you spending time developing a session layer, a
database connection layer, and then a security component.
Frameworks use a lot of best practices and design patterns to allow
developers to quickly use them to solve problems.
With this said, should you build a framework for your own use case?
This may not be necessary since all frameworks nowadays provide a way
to install any packages you might need but are not present already within
the framework. They also allow you to build custom layers by extending
the framework or plugin systems. If they are open source, if a need arises,
you can fork them and use the foundations of existing frameworks to build
upon them.
232
Chapter 13 Introduction to Frameworks
3. Decoupled patterns
4. Updated patches
5. Task automation
233
Chapter 13 Introduction to Frameworks
3. Learning curve
234
Chapter 13 Introduction to Frameworks
MVC Pattern
MVC stands for the Model, View, and Controller Pattern. It’s a very handy
and useful design pattern that many frameworks use for separation of
concerns. In previous chapters, you divided your code into UI, routing,
processing, and a business logic layer. Similarly, frameworks separate out
code into these logical structures and allow integration and control flow
between them through many standard, evolved, and secure practices.
As shown in Figure 13-1, when any request is received by a PHP server,
it hits the controller, which is usually the routing layer responsible for
defining the GET, POST, and other REST verb-based API endpoints. The
controller functions for respective endpoints receive the request and
then call the Model layer to fetch any data or run any business logic after
fetching data from another service. After the controller receives this data,
it sends it to the View layer, which contains your UI code and generates
the dynamic UI based on the model data sent to it. Once the View layer is
processed, this is sent as response back to the browser or user.
235
Chapter 13 Introduction to Frameworks
2. Dependency injection
3. Authentication/authorization
4. Session management
5. Database libraries
Frameworks provide database libraries to connect to
a variety of databases.
236
Chapter 13 Introduction to Frameworks
6. Test framework
7. Package management
8. Other
237
Chapter 13 Introduction to Frameworks
2. FULLSTACK-based frameworks
1. Micro frameworks:
Example: Slim
2. Full-fledged frameworks
Example: Laravel
Role of Composer
With the emergence of many frameworks, there was a need to also have many
third-party libraries for integration to different APIs. They can be integrated
into frameworks through extensions and following framework-specific
238
Chapter 13 Introduction to Frameworks
239
Chapter 13 Introduction to Frameworks
1. Autoloading
2. Interfaces
Associated PSRs:
3. HTTP
240
Chapter 13 Introduction to Frameworks
Associated PSRs:
4. Coding styles
Associated PSRs:
PHP Frameworks
The following are a few popular and widely used PHP frameworks. You will
use a few of them in later chapters.
• Laravel, https://laravel.com/
• Codeigniter, www.codeigniter.com/
• Symfony, https://symfony.com/
• Cakephp, https://cakephp.org/
• Laminas, https://getlaminas.org/
241
Chapter 13 Introduction to Frameworks
Choosing a Framework
With a plethora of frameworks available, it may be a bit confusing. How do
you select the right one? Here are a few points to consider:
3. Learning curve
Timelines of projects play a major role in terms
of framework choice. Pick a framework that has
a suitable learning curve so you can quickly start
building your project.
4. Documentation
242
Chapter 13 Introduction to Frameworks
5. Testing framework
6. Community support
7. Active release/development
8. Licenses
9. Customization/extensibility
243
Chapter 13 Introduction to Frameworks
12. Blogs/tutorials
244
Chapter 13 Introduction to Frameworks
Summary
In this chapter, you learned why frameworks are an important part of the
software development life cycle and make the life of developers easier and
more fun by allowing them to reuse existing components of a framework to
quickly start building new features and innovations. You explored why the
choice of a framework is very important. It must be done by considering a
variety of key points as well as the application to be built.
In the next chapter, you will focus on the Laravel PHP framework,
which is a very popular web application framework that is easy to use and
has an elegant syntax.
245
CHAPTER 14
Introduction
to Laravel
Lately the development of web applications and websites has become
more and more simple as developers make use of development tools. Let’s
explore which PHP framework can support web developers when building
new web projects and applications.
In this chapter, you will focus on the Laravel PGP framework, which
is a very popular web application framework that is easy to use and
offers an elegant syntax. It helps you with common tasks such as a fast
routing engine, real-time event broadcasting, database-agnostic schema
migrations, and more.
This chapter consists of the following sections:
• Introduction to Laravel
• Installing Laravel
• Database Migrations
• Controller Route
Introduction to Laravel
Laravel is a modern PHP framework based on the MVC design pattern. An
excerpt from the website explains it the best: “Laravel is a web application
framework with expressive, elegant syntax. We’ve already laid the
foundation—freeing you to create without sweating the small things.”
Installing Laravel
There are many ways Laravel can be installed. They can be found
at https://laravel.com/docs/9.x/installation#your-first-
laravel-project.
You will be following the simplest one to get you up and running.
Please make sure these prerequisites are installed before proceeding:
• PHP
• Composer
To start a new project with the name of blog-app, run the following
command:
The project structure looks like Figure 14-1 without the .git directory.
248
Chapter 14 Introduction to Laravel
cd blog-app
php artisan serve
249
Chapter 14 Introduction to Laravel
250
Chapter 14 Introduction to Laravel
This helps to have a repeatable data structure that can be readily used
by other team members to get quickly onboarded and set up the project
and also to create different environments for running projects like dev,
staging, and production. An added benefit is having a versioned schema
of your database and tables to understand and maintain the history of
changes for auditing and other such purposes.
Before you start setting up the migration aspect of Laravel, you must
configure the database configuration settings. They can be found in the file
config/database.php. Let’s review the contents of this file.
The default connection uses the mysql adapter, which suits your setup.
Reviewing the connections section, you see the configs specific to the
mysql connection.
'connections' => [
'sqlite' => [
...
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', ''),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
251
Chapter 14 Introduction to Laravel
The url, host, and port values are taken from the .env environment
file. This is a good practice, rather than hard-coding the secret values in
scm. To set the right values, open up .env file in the project root. You will
find the following section:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Once updated, make sure to clear the cache and update the config
cache with this change by running the following commands:
252
Chapter 14 Introduction to Laravel
Replace DB_DATABASE with your blog value and also set a DB_USERNAME
and DB_PASSWORD relevant to your MySQL setup.
Database Migrations
Laravel provides a command to create migrations:
You will create a table called users to store user data. Run the following
command to accomplish this:
The create and table options suggest creating a table in the database
and the name of the table.
On running git status, you’ll see a new file created at database/
migrations/2022_07_31_095213_create_users_table.php. The name
may be similar for you, except the prefix, which adds a timestamp value
to it. This does not create the table yet in the database. Let's review the
contents of this file.
253
Chapter 14 Introduction to Laravel
2022_07_31_095213_create_users_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
254
Chapter 14 Introduction to Laravel
From this default template, you can see two functions named up and
down. up is used to execute the current change in a migration and down is
used to revert the change. Inside the up function you can see the create
call with two fields, id and timestamps. Let’s execute the migration to
see the change reflected in your database. Before running the following
command, please make sure to remove any preexisting migration files
that might have come with the initial setup in the database/migrations
directory. Also, make sure your vendor/laravel/sanctum/database/
migrations directory is empty too.
255
Chapter 14 Introduction to Laravel
Reviewing the users table schema shown in Figure 14-8, you see that
it has a primary key id and two timestamp fields. You may need a few
more fields like name, email, and password. You’ll add them in following
section.
<?php
256
Chapter 14 Introduction to Laravel
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
};
257
Chapter 14 Introduction to Laravel
Let’s update the up method to contain the changes you want to bring
in this migration and the down method with the reverse changes so as to
remove them in case of a rollover:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('name');
$table->string('email');
$table->string('password');
});
}
258
Chapter 14 Introduction to Laravel
Since the users table is set up, you can now create the user registration
feature. There are three subfeatures of it functionality-wise that you
will build:
Controller Route
When you visit http://localhost:8000/register, you get the page
displayed in Figure 14-12, which is 404 not found, since you do not yet
have a route for this URL in your controller.
259
Chapter 14 Introduction to Laravel
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------
------------
| Web Routes
|--------------------------------------------------------------
------------
|
| Here is where you can register web routes for your
application. These
| routes are loaded by the RouteServiceProvider within a
group which
260
Chapter 14 Introduction to Laravel
Route::get('/', function () {
return view('welcome');
});
Route::get('/register', function () {
return view('register');
});
Inspecting this code, it is evident that get specifies the REST API
verb and /register the relative URI path for the get request. When the
controller intercepts a get request to the /register path, it will return the
register.blade.php page through a call to view('register').
Save the file and then visit http://localhost:8000/register and you
should see the output shown in Figure 14-13.
261
Chapter 14 Introduction to Laravel
You will develop the registration form later. For now, let’s create a
sample view page for the registration success page and the other route for
accepting the form submit request for registration submission.
The registration success page is at resources/views/registration_
success.blade.php.
Route::post('/register', function () {
return view('registration_success');
});
The above route is for a post route request sent to the /register
path and it returns the registration_success page. You will process the
data later.
To test this change, either open a terminal with the curl command
or Postman. Postman is a UI interface to run API requests. Further
documentation related to its installation and usage can be found
at https://learning.postman.com/docs/getting-started/
introduction/.
curl request:
262
Chapter 14 Introduction to Laravel
263
Chapter 14 Introduction to Laravel
264
Chapter 14 Introduction to Laravel
Registration Page
This creates a basic form HTML element with a form action URL set
to the /register route and a csrf token for XSS protection, as you can see
from the dev tools inspection in Figure 14-16.
Next, let’s add a few fields that a user should fill in when registering.
1. Name field
{{ Form::label('name', 'Name'); }}
{{ Form::text('name'); }}
2. Email field
{{ Form::label('email', 'Email'); }}
{{ Form::email('email', $value = null, $attributes =
array()); }}
3. Password field
{{ Form::label('password', 'Password'); }}
{{ Form::password('password'); }}
4. Submit button
{{ Form::submit('Register'); }}
265
Chapter 14 Introduction to Laravel
Registration Page
<br/>
<br/>
{{ Form::open(array('url' => 'register')) }}
{{ Form::label('name', 'Name'); }}
{{ Form::text('name'); }}
<br/>
<br/>
{{ Form::label('email', 'Email'); }}
{{ Form::email('email', $value = null, $attributes =
array()); }}
<br/>
<br/>
{{ Form::label('password', 'Password'); }}
{{ Form::password('password'); }}
<br/>
<br/>
{{ Form::submit('Register'); }}
{{ Form::close() }}
266
Chapter 14 Introduction to Laravel
Try filling in the field details with some sample values and click
the Register button to see the form POST submit request in action. On
submitting, it will look like Figure 14-18.
use Illuminate\Http\Request;
....
267
Chapter 14 Introduction to Laravel
If you want to create a migration file at same time, please add the
--migration option.
<?php
268
Chapter 14 Introduction to Laravel
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
To add more fields, such as name, email, and password, add the
following code to the class body:
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
];
269
Chapter 14 Introduction to Laravel
Now your User model is ready to be used. To use the User model in
your controller, update routes/web.php with the following namespace to
declare the User model:
use App\Models\User;
....
This will save the user details in the user table and return the
registration success template to the user. Notice you are using the Hash
helper to one-way hash the password so that the password is stored in an
encrypted format in database for security purpose. The output is shown in
Figure 14-20.
Let’s also check the database for the user details stored with an
encrypted password, as shown in Figure 14-21.
270
Chapter 14 Introduction to Laravel
Summary
In this chapter, you went through the essential elements to get started with
Laravel. You explored some of the main Laravel features but in general
there are many more that you will find handy, along with a plethora of
packages that are present in the Composer repository. Always check
the documentation of Laravel to see if there is an existing component,
helper, or library that can helps you with your task before checking the
Composer libraries or creating a custom library. This will save you a lot of
time in terms of development and maintenance. Laravel is continuously
improving, so always follow Laravel news, email lists, and newsletters to
stay up to date.
In the next chapter, you will focus on another PHP framework named
Symfony, which is a very popular PHP framework already used by
thousands of web applications.
271
CHAPTER 15
Introduction
to Symfony
In the previous chapters, you learned how to use Lavarel, which is a web
application framework used with PHP. In this chapter, you will focus on
Symfony, which is a very popular PHP framework already used to develop
websites and applications, including a very nice number of reusable PHP
components.
This chapter consists of the following sections:
• Introduction to Symfony
• Installing Symfony
Introduction to Symfony
Symfony is a full-stack framework built using a standard set of reusable
components. It’s a project where you can choose to use some of its
components or use the full stack.
It was created by Fabien Potencier in 2005 and is sponsored
by SensioLabs. In Symfony’s own words, “Symfony is a set of PHP
Components, a Web Application framework, a Philosophy, and a
Community - all working together in harmony” (https://symfony.com/
what-is-symfony)
1. A toolbox
2. A process to do things
A community:
274
Chapter 15 Introduction to Symfony
2. Ease of use
Symfony is very easy to use because it is very flexible
to any developer needs and is also very accessible. It
comes with a lot of documentation and is supported
by a strong community of professionals. It is also
very easy to use for beginners because it includes
embedded best practices.
3. Stable
The release cadence of Symfony makes sure to
maintain compatibility between minor versions of all
releases and also provides three-year support for all
major Symfony versions. This enables a stable and
sustainable model that you can trust.
4. Extensible
The integral central part of Symfony is made of
reusable components that can be used in other
projects or frameworks. This enables Symfony to
be very flexible and also extensible with changes to
the core behavior of the framework. Along with this,
Symfony leverages Composer to integrate the ever-
growing list of open source packages, thus enabling
developers to easily enrich its ecosystem.
275
Chapter 15 Introduction to Symfony
5. Fast
Fast is something everyone desires in terms of
performance, but it is very hard to achieve. Symfony
was built from the start to be fast with an emphasis
on performance.
6. Dependency injection
Dependency injection is a core concept. It allows you
to instantiate and use different components in the
runtime. Symfony uses it to provide a centralized way for
different objects to be initialized and provided in your
application, thus enabling simplicity and modularity.
7. Modular elements
Symfony provides many out-of-the-box modular
components for managing security, sessions, ORM
features, forms, and a templating engine that can be
included and fitted into use with Symfony with very
little effort.
8. Profiler tool
The Profiler tool is part of every web page and is
displayed at the bottom of all your pages. It provides
profile information in a variety of contexts, which are
discussed in coming sections. This is a very important
tool in every developer’s toolset. See Figure 15-1.
In Figure 15-1, you can see a toolbar with summary statistics. It’s the
development toolbar displayed by Symfony in debug mode and it contains
many details for each unique page. Figure 15-2 shows the controller route, API
response status, request time, memory usage, errors in form, and error logs.
276
Chapter 15 Introduction to Symfony
277
Chapter 15 Introduction to Symfony
Clicking on any one of them lets you further delve into the details.
For example, Figure 15-3 shows that clicking on the request panel reveals
further details related to the request.
On the left panel, you can also access further parts of the details related
to the current page you are trying to access.
Installing Symfony
There are a variety of ways by which Symfony can be installed. Refer to
https://symfony.com/doc/current/setup.html.
You will be following the simplest one to get you up and running.
Please make sure these prerequisites are installed before proceeding:
Before you create a basic Symfony project in the next chapter, let’s
install the Symfony CLI, which is very helpful in many tasks. Based on
the operating system, there are different ways to install it; see https://
symfony.com/download.
In a Ubuntu/Debian system, it can be run using the following
commands:
279
Chapter 15 Introduction to Symfony
Once the Symfony CLI is installed, you can use it to verify if your
system meets all requirements for a Symfony application by running the
following command:
symfony check:requirements
280
Chapter 15 Introduction to Symfony
281
Chapter 15 Introduction to Symfony
cd basic-starter-app
symfony server:start
282
Chapter 15 Introduction to Symfony
Summary
In this chapter, you learned about Symfony, a modern framework that can
be used by you to build websites. It provides a flexible core and an ever-
growing ecosystem of packages. You learned when to use this framework
and how to use it.
In the next chapter, you will learn how to develop a basic Symfony
application.
283
CHAPTER 16
A Basic Symfony
Application
In the previous chapter, you installed and explored the Symfony PHP
framework. In this chapter, you will focus on developing a basic Symfony
application.
This chapter consists of the following sections.
• Database Migrations
• Controller Route
symfony check:security
Once the project has been created, start it using the following
commands:
cd blog-app
symfony server:start
286
Chapter 16 A Basic Symfony Application
287
Chapter 16 A Basic Symfony Application
288
Chapter 16 A Basic Symfony Application
289
Chapter 16 A Basic Symfony Application
290
Chapter 16 A Basic Symfony Application
DATABASE_URL="mysql://app:[email protected]:3306/app?serverV
ersion=8&charset=utf8mb4"
with
DATABASE_URL="mysql://root:[email protected]:3306/blog"
291
Chapter 16 A Basic Symfony Application
You will need an entity to represent your user object. Let’s create it by
running the following command:
This will ask the name of the entity, which in your case is User, and any
fields and their types to be defined.
The output of this command is shown in Figure 16-9.
292
Chapter 16 A Basic Symfony Application
Similarly, also add fields for email and password. Once done, simply
enter without entering any value. After making these changes, you’ll get a
success message, as shown in Figure 16-10.
293
Chapter 16 A Basic Symfony Application
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(length: 255)]
private ?string $email = null;
#[ORM\Column(length: 255)]
private ?string $password = null;
294
Chapter 16 A Basic Symfony Application
return $this;
}
return $this;
}
return $this;
}
}
You’ve added all the defined columns into attributes for the User
attributes. Using this you can now create your migration to create the table
in the database. Run the following:
295
Chapter 16 A Basic Symfony Application
Let’s review the migration file created (in our case, it’s at migrations/
Version20220821091914.php):
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20220821091914 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
296
Chapter 16 A Basic Symfony Application
297
Chapter 16 A Basic Symfony Application
The file has up and down methods for migrate and rollback. It contains
your create table SQL. This is very handy as you do not need to create the
SQL statement yourself. Run this migration:
Let’s check phpMyAdmin to review the creation of the user and the
migrations table, as shown in Figures 16-14 and 16-15.
298
Chapter 16 A Basic Symfony Application
With these changes, if you now start the Symfony server, you will see a
few logs related to connecting to the database and executing some system-
level queries.
299
Chapter 16 A Basic Symfony Application
Now, since the user table is set up, you can create the user registration
feature. There are three subfeatures of it functionality-wise that you
will build:
Controller Route
Let’s see now how to work with the Controller Route to load the
registration view form and accept form submit requests.
When you visit the http://localhost:8000/register URL, you get
the page shown in Figure 16-17, a 404 not found code, since you do not
have a route for this URL in your controller.
300
Chapter 16 A Basic Symfony Application
If you see a "The metadata storage is not up to date, please run the
sync-metadata-storage command to fix this issue" message, please run the
following command to fix it:
src/Controller/UserController.php
templates/user/index.html.twig
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\
AbstractController;
use Symfony\Component\HttpFoundation\Response;
301
Chapter 16 A Basic Symfony Application
use Symfony\Component\Routing\Annotation\Route;
Let’s modify the route from /user to /register and reload your
browser at http://localhost:8000/register.
302
Chapter 16 A Basic Symfony Application
You will develop the registration form later. For now, let’s create a
sample view page for registration success page and another route for
accepting the form submit request for registration submission.
See the registration success page at templates/user/registration_
success.html.twig. You have been successfully registered!
Update the GET route with the following code at src/Controller/
UserController.php to add a POST request handler:
....
use Symfony\Component\HttpFoundation\Request;
....
The above route now handles both GET and POST requests for the /
register route, and when a POST request is sent to the /register path, it
returns the registration_success page. You have left out the processing of
data and will complete it later.
303
Chapter 16 A Basic Symfony Application
304
Chapter 16 A Basic Symfony Application
...
use App\Entity\User;
...
You will now build the form using the form builder method and bind it
to the $user instance.
$form = $this->createFormBuilder($user)
// Bind $user to the $form instance
// Associate entity name field to $form and show it as
a text type field
305
Chapter 16 A Basic Symfony Application
->add('name', TextType::class)
// Associate entity email field to $form and show as an
email type field
->add('email', TextType::class)
// Associate entity password field to $form and show as
a password type field
->add('password', PasswordType::class)
// Finally add a submit button
->add('save', SubmitType::class, ['label' =>
'Register'])
->getForm();
Once the form builder instance is created, you need to associate and
pass $form onto the view layer, which is user/index.html.twig. This is
done by updating the index render call with the following:
return $this->renderForm('user/index.html.twig', [
'form' => $form,
]);
{% extends 'base.html.twig' %}
{% block body %}
{{ form(form) }}
{% endblock %}
In this code, you have replaced the title and block body with a simple
call to form(form), which loads the passed-in form. This creates a basic
form HTML element with three fields and a csrf token for XSS protection,
as can be seen from the dev tools inspection shown in Figure 16-22.
306
Chapter 16 A Basic Symfony Application
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\
AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
307
Chapter 16 A Basic Symfony Application
->add('email', EmailType::class)
->add('password', PasswordType::class)
->add('save', SubmitType::class, ['label' =>
'Register'])
->getForm();
if ($request->isMethod('POST')) {
return $this->render('user/registration_success.
html.twig', [
'controller_name' => 'UserController',
]);
}
return $this->renderForm('user/index.html.twig', [
'form' => $form,
]);
}
}
Try filling in the field details with some sample value and click the
Register button to see the form’s POST submit request in action.
On submitting, it will display the output shown in Figure 16-23.
308
Chapter 16 A Basic Symfony Application
Now that you have been able to post data to a route end, you can parse
the different values. These values are available as part of the Request
object and can be used to associate with the form entity. Let’s see it in
practice. Make the following changes to the index method after $form is
instantiated:
...
$form->handleRequest($request);
...
Now with above change, $form, which has been associated with your
User entity, has the submitted values filled into the respective fields and
can be used to fetch the User entity set to these values.
$user = $form->getData();
Before you fetch the form data, you need to validate if all is well and
also you need to replace the isMethod function call check with a handy
method which the form provides to check if it was submitted to give you an
idea that this is a POST request:
309
Chapter 16 A Basic Symfony Application
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\PasswordHasher\Hasher\
UserPasswordHasherInterface;
...
$user->setPassword(
$passwordHasher->hashPassword($user, $user-
>getPassword())
);
$entityManager = $doctrine->getManager();
$entityManager->persist($user);
$entityManager->flush();
This will save the user details in the user table and return the
registration success template to the user. Notice you are using Hash helper
to one-way hash the password so that the password is stored in encrypted
format in the database for security purposes.
The whole code should now look like the following:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\
AbstractController;
use Symfony\Component\HttpFoundation\Request;
310
Chapter 16 A Basic Symfony Application
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User;
use Symfony\Component\PasswordHasher\Hasher\
UserPasswordHasherInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
$form->handleRequest($request);
311
Chapter 16 A Basic Symfony Application
return $this->render('user/registration_success.
html.twig', [
'controller_name' => 'UserController',
]);
}
return $this->renderForm('user/index.html.twig', [
'form' => $form,
]);
}
}
Let’s also check the database to see the user details stored with an
encrypted password, as shown in Figure 16-24.
312
Chapter 16 A Basic Symfony Application
Summary
In this chapter, you went through the essential elements to start with
Symfony. You set up and configured a database and added data to it. You
also learned about some of major features of Symfony. However, there are
many more that you will find handy, along with a plethora of packages in
the Composer repository.
This is the last chapter of this book. You’ve learned the basics of PHP
version 8!
313
Index
A array_chunk(), 93, 94
array_column(), 94, 95
Abstract classes, 33, 34, 39–41, 48
array_combine(), 95
ACTUAL single quote, 53
array_count_values(), 95
API-specific documentations, 278
array_diff(), 98, 99
Application programming interface
array_diff_assoc(), 96
(API), 26, 29, 30, 229, 235,
array_diff_key(), 96
237, 239, 261, 276, 278, 304
array_diff_uassoc(), 97
app/Models/User.php, 268
array_diff_ukey(), 97, 98
Arbitrary cookie, 163
array_fill(), 99, 100
array_change_key_case(), 93
array_fill_keys(), 99
array_chunk(), 93, 94
array_filter(), 100, 101
array_column(), 94, 95
array_flip(), 101
array_combine(), 95
array_intersect(), 104
array_count_values(), 95
array_intersect_assoc(), 101, 102
array_diff(), 98, 99
array_intersect_key(), 102
array_diff_assoc(), 96
array_intersect_uassoc(), 102, 103
array_diff_key(), 96
array_intersect_ukey(), 103, 104
array_diff_uassoc(), 97
array_is_list(), 104, 105
array_diff_ukey(), 97, 98
array_key(), 137
array_fill(), 99, 100
array_key_exists(), 105, 137
array_fill_keys(), 99
array_key_first(), 105
array_filter(), 100, 101
array_key_last(), 106
ARRAY_FILTER_USE_BOTH, 100
array_keys(), 106
ARRAY_FILTER_USE_KEY, 100
array_map(), 107
array_flip(), 101
array_merge(), 108, 109
Array functions
array_merge_recursive(), 108
array(), 128, 129
array_multisort(), 109
array_change_key_case(), 93
316
INDEX
317
INDEX
318
INDEX
319
INDEX
320
INDEX
G
__get() method, 94 K
GET method, 26, 29, 31, 75, 76, 229 Key, 87, 88
PHP CRUD GET method, 221 key_compare_func, 97, 98, 103,
getMenuName() method, 169 104, 122, 124
Getters, 24, 166 krsort(), 92, 137, 138
git status, 253 ksort(), 92, 138, 139
H L
Hash helper, 270, 310 Laravel DB table creation, 253
header.php, 22 Laravel PGP framework
htmlspecialchars PHP function, 28 common tasks, 247
Hyper Text Transfer Protocol controller route, 259–262, 264
(HTTP), 25–27, 75, 240 database migrations
command, 253
create and table options, 253
I, J default template, 255
inc/ directory, 22 directory, 255
include_once function, 21, 31 migrations table schema, 255
Indexed array, 86, 94, 127, 137, 147 modification, 259
index_key, 94 new migration file
Individual objects, 71, 165 creation, 256
Inheritance, 33, 38, 39, 44, 48 output, 258, 259
Instagram plugin, 29 phpMyAdmin, 255
Integer, 50–52, 64, 94, 97, 98, 103, reverse changes, 258
104, 107, 111, 118, 120–125, timestamp value, 253
129, 145, 146, 165, 208, 209 user registration feature, 259
321
INDEX
322
INDEX
323
INDEX
324
INDEX
325
INDEX
326
INDEX
327
INDEX
328
Index
V Y, Z
Validation, 25, 171–191, 267, YEAML files, 11
274, 305 Yet Another Markup Language
value_compare_func, 120, 124, 125 (YAML), 9, 11, 14
329