PHP 8 Basics: For Programming and Web Development Gunnard Engebreth download
PHP 8 Basics: For Programming and Web Development Gunnard Engebreth download
or textbooks at https://ebookmass.com
_____ Follow the link below to get your download now _____
https://ebookmass.com/product/php-8-basics-for-programming-
and-web-development-gunnard-engebreth/
https://ebookmass.com/product/php-8-basics-for-programming-and-web-
development-1st-edition-gunnard-engebreth/
https://ebookmass.com/product/an-introduction-to-php-learn-php-8-to-
create-dynamic-websites-1st-edition-mark-simon/
https://ebookmass.com/product/an-introduction-to-php-learn-php-8-to-
create-dynamic-websites-mark-simon/
JavaScript for Web Developers: Understanding the Basics
1st Edition Mark Simon
https://ebookmass.com/product/javascript-for-web-developers-
understanding-the-basics-1st-edition-mark-simon/
https://ebookmass.com/product/how-javascript-works-master-the-basics-
of-javascript-and-modern-web-app-development-1st-edition-jonathon-
simpson-2/
https://ebookmass.com/product/how-javascript-works-master-the-basics-
of-javascript-and-modern-web-app-development-1st-edition-jonathon-
simpson/
https://ebookmass.com/product/introducing-rescript-functional-
programming-for-web-applications-1st-edition-danny-yang/
Gunnard Engebreth and Satej Kumar Sahu
PHP 8 Basics
For Programming and Web Development
Gunnard Engebreth
Madison, WI, USA
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Apress imprint is published by the registered company APress
Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
This book is dedicated to my wife Erica and to my boys Trip and
Wyatt.Also, you the reader. Thank you!
Jesus looked at them and said, “With man this is impossible, but with God
all things are possible.”
—Matthew 19:26!
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.
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.
Who This Book Is For
The book assumes you have some web development and DB handling
knowledge. The book is written mainly for the beginning web
developer who wants to learn how to use PHP version 8 and how it can
be used with MySQL and PHP frameworks like laravel and Symfony. It
also assumes you have some knowledge of programing language
frameworks and how and when you should use them with PHP.
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 introduced and utilized two different PHP Frameworks named
Laravel and Symfony, which will be needed for the examples of this
book.
1. Getting Started
Gunnard Engebreth1 and Satej Kumar Sahu2
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.
Installing Docker
Let’s get Docker installed on your operating system of choice. Here’s how to do it.
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.
2. When prompted, ensure the Enable Hyper-V Windows Features. If you have previously
configured WSL and are comfortable with it, then make sure the “Install required
Windows components for WSL 2” option is selected on the Configuration page.
3. Follow the instructions in the installation wizard to authorize the installer and proceed
with the install.
4. When the installation is successful, click Close to complete the installation process.
5. If your admin account is different to your user account, you must add the user to the
docker-users group. Run Computer Management as an administrator and navigate to
Local Users and Groups ➤ Groups ➤ docker-users. Right-click to add the user to the
group. Log out and log back in for the changes to take effect.
Docker Desktop does not start automatically after installation. To start Docker Desktop,
search for Docker, and select Docker Desktop in the search results. When the whale icon in
the status bar stays steady, Docker Desktop is up, running, and accessible from any terminal
window.
Mac OS
Go to https://docs.docker.com/docker-for-mac/install/, shown in Figure 1-
2.
Double-click Docker.dmg to open the installer and then drag the Docker icon to the
Applications folder, as shown in Figure 1-3.
Double-click Docker.app in the Applications folder to start Docker. (In Figure 1-4,
the Applications folder is in grid view mode.)
Figure 1-4 Docker Applications folder
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 distributions. If you are using
Debian/Ubuntu, you can follow these instructions
(https://docs.docker.com/engine/install/ubuntu/):
1) Ensure that any older installation is removed from the system.
<code>
sudo apt-get remove docker docker-engine docker.io containerd
runc
</code>
2) Update the apt package index and install packages to allow apt to use a repository over
HTTPS.
<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>
4) Use the following command to set up the stable repository. To add the nightly or test
repository, add the word nightly or test (or both) after the word stable.
<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>
5) Update the apt package index and install the latest version of Docker Engine and
container.
<code>
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
</code>
If you have any difficulties or need to install a specific version of Docker for your system,
please visit https://docs.docker.com/engine/install/ where they cover many
more options and configurations than is possible in the scope of this section.
Once Docker is installed, you will need to install docker-compose. Compose is a tool for
defining and running multi-container Docker applications. Compose allows you to define an
application within the confines of a YAML (Yet Another Markup Language) file. This allows
you to spin up all of the defined services for your Docker container with a single command.
This is often used within development teams to ensure version control and maintain use of
third-party applications. Other features of Compose are
Multiple isolated environments on a single host
Preserving volume data when containers are created
Only recreating containers that have changed
Variables and moving a composition between environments
More on these features can be found at
https://docs.docker.com/compose/#features.
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.
1) For Linux users, run this command to download the current stable release of Docker
Compose:
<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>
Note If the command docker-compose fails after installation, check your path. You can
also create a symbolic link to /usr/bin or any other directory in your path.
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>
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>
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>
This command shows you any containers that Docker has or is currently using. Here you
can see the mysql, nginx, and beginning php containers. One last thing to verify is that you can
run PHP from within the PHP container. From the command line, type
<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>
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.
© Gunnard Engebreth, Satej Kumar Sahu 2023
G. Engebreth, S. K. Sahu, PHP 8 Basics
https://doi.org/10.1007/978-1-4842-8082-9_2
2. PHP Fundamentals
Gunnard Engebreth1 and Satej Kumar Sahu2
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.
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
Variable names are case-sensitive ($pants and $PANTS are two
different variables).
Unlike other programming languages, PHP does not have a specific
command for declaring variables. You must pay attention to where and
how variables are declared and used.
Let's write some code and see how the browser handles it. Go into
your beginning-php8-and-mysql directory and under chapter
2, create a file called newtest.php. Inside of this file, write
<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>
<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.
Speaking of errors, let’s go ahead and get comfortable with errors
and how they can be useful to us instead of annoyances.
Using Errors As Tools
In PHP, you do not always see the errors that occur. This is because
there are three different levels with configurations for how and where
to display them. Let’s go back into vartest.php and add these lines
to the top:
<?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
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
The next line of ini_set() is used in PHP to overwrite
configuration options that are set in the php.ini file. This is helpful
when you need to do one-off configurations or are on a server where
you do not have access to the ini file. The next line is the error line. Do
you see it? Go ahead and pull up the file in your browser and see what it
says.
<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>
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>
<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>
<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>
<?php
class UserClass
/* User variables */
var $firstName;
var $LastName;
/* Member functions */
function setFirstName($firstName){
$this->firstName = $firstName;
}
function getFirstName(){
echo $this->firstName;
}
function setLastName($lastName){
$this->lastName = $lastName;
}
function getLastName(){
echo $this->lastName;
}
}
</code>
<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>
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.
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&food=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';
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).
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:
Stock ticker -> Bloomberg API
Tweet stream -> Twitter API
Instagram gallery -> Instagram API
Other documents randomly have
different content
tahansa saattoi syöksyä metsästä. Kun komppaniassa oli vähän
miehiä ja vartiopaikkoja paljon, täytyi siinä kitua kolme, neljä, jopa
muutaman kerran kuusikin tuntia perätysten, ja kun vihdoin pääsi
lähtemään kotiin, niin ei siihen enää tahtonut kyetä, niin oli vilusta
jäykkä. Muistan joskus ajatelleeni, etteivät meidän ylennetyt
miehemme sentään oikeastaan tunteneet, mitä oli olla tavallisena
sotilaana. Heidän ei tarvinnut luonnollisestikaan ottaa osaa työhön,
ei myöskään vartiointiin, he ainoastaan järjestelivät ja komentelivat.
Olivathan he tosin olleet Saksassa alusta alkaen, mutta niin oli moni
jääkärikin; kaiken lisäksi heillä oli paljoa parempi palkka. Eivät he
olleet kokeneet, mitä oli maata tuntikausia märkänä, jäätyvällä
suolla. — Mutta lienee ollut paljon, josta vuorostamme me emme
tietäneet.
*****
1.
BERLINIIN.
*****
NAPA.
— Niin.
— Napa tulee!
Luonnollisesti.
Olin pohjoisessakin.
Olinko hiihtänyt?
Tietysti.
En.
Kittilässä sitten?
*****
— Sanokaa, etteivät pojat kävele yhtä jalkaa. Siitä näkee heti, että
he ovat sotilaita.
— Ymmärrän.
3.
BERLININ PIKKUPORVAREITA.
Toverini M. ja minä keksimme verrattain hauskan asunnon Pension
N. N:stä, Potsdamerstrassen varrelta. Täysihoito maksoi ainoastaan
3: 50 Saksan markkaa vuorokaudelta ja ruoka kävi laatuun, ainakin
jääkärille, vaikka sitä saikin jotakuinkin niukasti.
*****
— Mihinkä niin?
— Meitä on kutsuttu vierailulle. Oi, kuinka hauskaa!
Steglitzerstrasse 20. Teidän suomalaiset toverinne ovat kutsuneet.
Juuri nyt tuli sana… Tietysti te tulette mukaan.
— Kuka on kutsunut?
ebookmasss.com