The PHP Workshop: Learn to build interactive applications and kickstart your career as a web developer
By Alexandru Busuioc, David Carr, Markus Gray and
()
About this ebook
Get to grips with the fundamentals of PHP programming and learn to build dynamic, testable PHP web applications with the help of real-world examples and hands-on projects
Key Features- Start building modern and testable PHP web applications
- Master the basic syntax and fundamental features of PHP
- Implement object-oriented programming to write modular, well-structured code
Do you want to build your own websites, but have never really been confident enough to turn your ideas into real projects? If your web development skills are a bit rusty, or if you've simply never programmed before, The PHP Workshop will show you how to build dynamic websites using PHP with the help of engaging examples and challenging activities.
This PHP tutorial starts with an introduction to PHP, getting you set up with a productive development environment. You will write, execute, and troubleshoot your first PHP script using a built-in templating engine and server. Next, you'll learn about variables and data types, and see how conditions and loops help control the flow of a PHP program. Progressing through the chapters, you'll use HTTP methods to turn your PHP scripts into web apps, persist data by connecting to an external database, handle application errors, and improve functionality by using third-party packages.
By the end of this Workshop, you'll be well-versed in web application development, and have the knowledge and skills to creatively tackle your own ambitious projects with PHP.
What you will learn- Set up a development environment and write your first PHP scripts
- Use inheritance, encapsulation, polymorphism and other OOP concepts
- Use HTTP and understand the request-response cycle of an application
- Perform file operations and interact with external databases
- Deal with application errors and handle exceptions
- Use third-party libraries and manage dependencies
- Connect your application to web services to allow for data exchange
This book on PHP for beginners will help you if you're just getting started with PHP. Although prior programming experience is not necessary, a basic understanding of HTML, CSS, and JavaScript will help you grasp the concepts covered more easily.
Related to The PHP Workshop
Related ebooks
PHP Examples, Part 2 Rating: 1 out of 5 stars1/5WordPress 3 Plugin Development Essentials Rating: 4 out of 5 stars4/5PHP Examples Part 3 Rating: 5 out of 5 stars5/5The Ruby Workshop: Develop powerful applications by writing clean, expressive code with Ruby and Ruby on Rails Rating: 0 out of 5 stars0 ratingsPHP 7 Programming Cookbook Rating: 0 out of 5 stars0 ratingsLearning PHP 7 Rating: 4 out of 5 stars4/5Mastering JavaScript Rating: 4 out of 5 stars4/5Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications, and libraries Rating: 3 out of 5 stars3/5HTML, CSS, Bootstrap, Php, Javascript and MySql: All you need to know to create a dynamic site Rating: 4 out of 5 stars4/5Introduction to PHP Web Services: PHP, JavaScript, MySQL, SOAP, RESTful, JSON, XML, WSDL Rating: 0 out of 5 stars0 ratingsPHP for Beginners: Your Guide to Easily Learn PHP In 7 Days Rating: 4 out of 5 stars4/5Instant SASS CSS How-to Rating: 5 out of 5 stars5/5PHP 7 Programming Blueprints Rating: 0 out of 5 stars0 ratingsJavaScript Unlocked Rating: 5 out of 5 stars5/5Bootstrap By Example Rating: 0 out of 5 stars0 ratingsMastering Bootstrap 4 Rating: 5 out of 5 stars5/5JavaScript Security Rating: 4 out of 5 stars4/5Bootstrap 4 Quick Start: A Beginner's Guide to Building Responsive Layouts with Bootstrap 4 Rating: 0 out of 5 stars0 ratingsModern JavaScript Applications Rating: 0 out of 5 stars0 ratingsLearning PHP 7 High Performance Rating: 0 out of 5 stars0 ratingsPHP 7: Real World Application Development Rating: 0 out of 5 stars0 ratingsLearning jQuery Rating: 4 out of 5 stars4/5JavaScript and JSON Essentials Rating: 5 out of 5 stars5/5Responsive Web Design with HTML5 and CSS3 - Second Edition Rating: 4 out of 5 stars4/5Web Developer's Reference Guide Rating: 0 out of 5 stars0 ratingsCreating your MySQL Database: Practical Design Tips and Techniques Rating: 3 out of 5 stars3/5Wordpress Web Application Development - Third Edition Rating: 0 out of 5 stars0 ratingsPHP Error Reporting: How To Do It Right Rating: 0 out of 5 stars0 ratings
Programming For You
Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsCoding All-in-One For Dummies Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsSQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Linux Command-Line Tips & Tricks Rating: 0 out of 5 stars0 ratingsPython QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsLearning JavaScript Data Structures and Algorithms Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsJavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5PYTHON PROGRAMMING Rating: 4 out of 5 stars4/5
Reviews for The PHP Workshop
0 ratings0 reviews
Book preview
The PHP Workshop - Alexandru Busuioc
The PHP Workshop
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Authors: Alexandru Busuioc, David Carr, Markus Gray, Vijay Joshi, Mark McCollum, Bart McLeod, and M A Hossain Tonu
Technical Reviewers: Jordi Martinez and Kristian Secor
Managing Editor: Rutuja Yerunkar
Acquisitions Editor: Sarah Lawton
Production Editor: Samita Warang
Editorial Board: Shubhopriya Banerjee, Bharat Botle, Ewan Buckingham, Megan Carlisle, Mahesh Dhyani, Manasa Kumar, Alex Mazonowicz, Bridget Neale, Dominic Pereira, Shiny Poojary, Abhishek Rane, Erol Staveley, Ankita Thakur, Nitesh Thakur, and Jonathan Wray
First Published: October 2019
Production Reference: 5230221
ISBN: 978-1-83864-891-6
Published by Packt Publishing Ltd.
Livery Place, 35 Livery Street
Birmingham B3 2PB, UK
Table of Contents
Preface
1. Introducing PHP
Introduction
Getting Started with PHP Web Development
Built-in Templating Engine
PHP in the Interactive Shell
Exercise 1.1: Printing Hello World to the Standard Output
Exercise 1.2: Printing Hello World by Executing a PHP File
Assigning and Using Variables
Creating and Assigning Variables to Print Simple Messages on the Web Browser
Exercise 1.3: Using Input Variables to Print Simple Strings
Exercise 1.4: Using the Built-in Server to Print a String
HyperText Markup Language
Cascading Style Sheets
Exercise 1.5: Creating a Login Form Page Using Bootstrap
Exercise 1.6: Printing PHP Code Output between HTML Tags
Using the Server Variable
Exercise 1.7: Displaying Server Information
Other Predefined Variables
Assignment by Value and by Reference
Exercise 1.8: Assigning a Variable by Reference and Changing its Value
Using isset to Check for Variable Declaration
Exercise 1.9: Using isset to Check whether a Variable Has Been Set
Activity 1.1: Displaying Query Strings in the Browser
Summary
2. Types and Operators
Introduction
What are Data Types?
Integers
Strings
Single and Double-Quoted Strings
Heredoc and Nowdoc Syntaxes
Floats
Boolean
Exercise 2.1: Using Simple Data Types
Arrays
Indexed and Associative Arrays
Adding and Removing Items from an Array
Exercise 2.2: Creating a Multidimensional Array
Scalar Types
Type Conversion
Exercise 2.3: Converting a Boolean to an Integer
Exercise 2.4: Converting an Integer to a String
Exercise 2.5: Converting Centimeters to Meters
Operators and Expressions
Arithmetic Operators
String Operators
Bitwise Operators
Assignment Operators
Comparison Operators
Increment/Decrement Operators
Logical Operators
Array Operators
Conditional Assignment Operators
Activity 2.1: Printing the BMI of a User
Summary
3. Control Statements
Introduction
Boolean Expressions
Boolean Constants
Logical Operators
The not Operator
The and Operator
The or Operator
The xor Operator
Short-Circuit Evaluation and Operator Precedence
The Precedence of Logical Operators
|| versus or
&& versus and
Comparison Operators
Branching
The if Statement
The if…else Statement
Exercise 3.1: Creating a Basic Script to Implement the if...else Test Case
Exercise 3.2: Implementing the Nested if...else Structure
The Ternary Operator
The if…elseif…else Statement
Exercise 3.3: Creating a Script Using the if... elseif... else Statement
The switch Case
Exercise 3.4: Creating a Script to Implement a Switch Case
Looping
Bounded Loops versus Unbounded Loops
The while Loop
Exercise 3.5: Printing the Numbers 1 to 10 Using a while Loop
The do…while Loop
Exercise 3.6: Converting a while Loop to a do...while Loop
The for Loop
Exercise 3.7: Using a for Loop to Print the Days of the Week
The foreach Loop
Exercise 3.8: Using a foreach Loop to Print the Days of the Week
Nesting Loops
Exercise 3.9: Using Nested foreach Loops
The break Statement
Exercise 3.10: Using a break Statement to Terminate a Loop's Execution
The continue Statement
Exercise 3.11: Using continue to Skip an Item in a List
Alternative Control Syntaxes
Using System Variables
Activity 3.1: Creating a Movie Listing Script to Print Movies per Director
Tips for Control Structures
Summary
4. Functions
Introduction
What is a Callable?
Exercise 4.1: Using Built-in Functions
Types of Callables
Language Constructs
Introduction to Built-In Functions
Finding Built-In Functions
Parameters and Return Values
Passing Parameters by Reference
Passing Scalar Variables by Reference
Optional Parameters
Exercise 4.2: Working with print_r()
A Varying Number of Parameters
Flag Parameters
Exercise 4.3: Using Built-In Functions with Arrays
Introduction to User-Defined Functions
Naming Functions
Documenting Your Functions
Namespaced Functions
Pure Functions
Scope
The $GLOBALS Superglobal Array
Exercise 4.4: Using the $GLOBALS array
The Single Responsibility Principle
The function Keyword
Identifier
Type Hints
The Spread Operator (…) with Type Hints
Parameters in User-Defined Functions
Return Types in User-Defined Functions
Signature
Returning a Value
Parameters and Arguments
Optional Parameters
Parameters Passed by Reference to Our Function
Default Values for Parameters
Exercise 4.5: Writing a Function that Adds Two Numbers
Variable Functions
Anonymous Functions
Using a Variable from Outside of Scope Inside an Anonymous Function
Exercise 4.6: Working with Anonymous Functions
Exercise 4.7: Creating Variable Functions
Exercise 4.8: Playing with Functions
Activity 4.1: Creating a Calculator
Summary
5. Object-Oriented Programming
Introduction
The Object-Oriented Approach
OOP Concepts
Classes
Instantiating a Class
Class Attributes
Class Constants
The $this Variable
Class Methods
Exercise 5.1: Using the Getter and Setter Methods
Constructor
Destructor
Exercise 5.2: Instantiating the Class and Printing the Details
Inheritance
Exercise 5.3: Implementing Inheritance
Access Modifiers
Exercise 5.4: Applying Access Modifiers
Static Fields and Methods
parent:: and self::
Exercise 5.5: Applying a Static Member
Class Abstraction
Exercise 5.6: Implementing an Abstract Class
Interfaces
Exercise 5.7: Implementing an Interface
Abstract Classes versus Interfaces
Class Type Hinting Plays a Role in Dependency Injection
Overriding
Attribute Overriding
Method Overriding
Exercise 5.8: Overriding an Inherited Method
Overloading
Attribute Overloading
Method Overloading
Exercise 5.9: Implementing Attribute and Method Overloading
Final Classes and Methods
Exercise 5.10: Implementing a Final Class and Methods
Traits
Exercise 5.11: Implementing Trait
Class Autoloading
Namespaces
Exercise 5.12: Implementing Namespaces
Activity 5.1: Building a Student and Professor Object Relationship
Summary
6. Using HTTP
Introduction
The Request-Response Cycle of a Web Application
A Typical HTTP Request
A Typical HTTP Response
Request Methods
GET HTTP Requests
POST HTTP Requests
Query Strings
PHP Superglobals
$_SERVER
Exercise 6.1: Dumping the $_SERVER Data
$_COOKIE
Exercise 6.2: Setting and Reading a Cookie
$_SESSION
Exercise 6.3: Writing and Reading Data from a Session
$_GET
Exercise 6.4: Using Query Strings in Web Pages
$_POST
Exercise 6.5: Sending and Reading POST Data
$_FILES
Exercise 6.6: Uploading a File and Validating its Type
Securing Input and Output Data
Best Practices
Sanitizing and Validating the User Input
Exercise 6.7: Sanitizing and Validating the User Input
Escaping the Output
Cross-Site Scripting (XSS)
Exercise 6.8: Securing against XSS
Cross-Site Request Forgery (CSRF)
Exercise 6.9: Securing against CSRF
Building an Application (Bootstrapping the Examples)
web/
src/
components/
handlers/
templates/
Exercise 6.10: Building an Application: The Home Page
Exercise 6.11: Building an Application: The Profile Page and the Login Form
Activity 6.1: Creating a Support Contact Form
Summary
7. Data Persistence
Introduction
File I/O Handling
Reading Files with PHP
A Simple File Read
Exercise 7.1: A Simple File Read (All at Once)
Reading Files with the fread Function
Exercise 7.2: Reading Files with the fread Function
Benchmark File Reading
Exercise 7.3: Benchmark File Reading
Reading Files Line by Line
Exercise 7.4: Reading Files Line by Line
Reading CSV Files
Exercise 7.5: Reading CSV Files
Downloading a File with PHP
Exercise 7.6: Downloading a File
Writing a File with PHP
Exercise 7.7: Writing to Files
Exercise 7.8: Appending Content in Files
Other Filesystem Functions
Deleting a File with PHP
Exercise 7.9: Deleting a File with PHP
Moving Files with PHP
Exercise 7.10: Creating Directories and Moving Files to the Archive
Copying Files Using PHP
Exercise 7.11: Copying Files
Databases
GUI Clients
Connecting to MySQL
Connecting to MySQL
Exercise 7.12: Connecting to MySQL
Creating a Database
Exercise 7.13: Creating a Database
Creating a Table
Exercise 7.14: Creating the Table
Inserting Data into a MySQL Database Table
Exercise 7.15: Inserting Data into a Table
SQL Injection
Prepared Statements
Using Prepared Statements
Exercise 7.16: Inserting Data Using Prepared Statements
Fetching Data from MySQL
Exercise 7.17: Fetching Data from MySQL
Updating Records in MySQL
Exercise 7.18: Updating Records in MySQL
Deleting Records from MySQL
Exercise 7.19: Deleting Records from MySQL
The Singleton Pattern
Activity 7.1: Contact Management Application
Summary
8. Error Handling
Introduction
Errors in PHP
Handling Errors
The Default Error Handler
Using a Custom Error Handler
Exercise 8.1: Using a Custom Error Handler
Exercise 8.2: Logging with the Custom Error Handler
Triggering a User-Level Error
Exercise 8.3: Triggering Errors
Logging Errors at Script Shutdown
Exercise 8.4: Logging Fatal Errors at Shutdown
Exceptions
Basic Usage
Exercise 8.5: Implementing Exceptions
Custom Exceptions
Exercise 8.6: Custom Exceptions
Custom Exception Handler
Using a Custom Exception Handler
Exercise 8.7: Using a Custom Exception Handler
Translating Errors to Exceptions
Exercise 8.8: Translating Errors to Exceptions
Exercise 8.9: Simple Exception Handling
Exercise 8.10: Better Usage of Exceptions
Activity 8.1: Handling System and User-Level Errors
Summary
9. Composer
Introduction
Dependency Management
Using Composer
Exercise 9.1: Getting Started with Composer
Initializing a Project
Exercise 9.2: Initializing a Project
Requiring Packages
Exercise 9.3: Adding Dependencies
Semantic Versioning
Applying Version Constraints
Exercise 9.4: Applying Version Constraints
The Lock File
Exercise 9.5: Re-Installing Vendor Files
Dev Dependencies
Exercise 9.6: Installing Development Dependencies
Packagist
Exercise 9.7: Discovering Packages on Packagist.org
Namespaces
Autoloading
Using Composer Packages
Exercise 9.8: Using PSR-4 to Load Classes
Exercise 9.9: Implementing Monolog
Activity 9.1: Implementing a Package to Generate a UUID
Summary
10. Web Services
Introduction
An Example Web Service
Selecting Third-Party APIs
RESTful Concepts
Request Formats
Exercise 10.1: JSON Encoding
HTTP Headers
Authentication and Authorization
Manual API Testing
Exercise 10.2: Manual API Testing with Insomnia
Making a Request with PHP
Exercise 10.3: Making a GET Request with Guzzle
Exercise 10.4: Sending a POST Request with Headers
Activity 10.1: Making Your Own POST Request to httpbin.org
Summary
Appendix
Preface
About
This section briefly introduces the coverage of this book, the technical skills you'll need to get started, and the hardware and software requirements required to complete all of the included activities and exercises.
About the Book
Do you want to build your own websites, but have never really been confident enough to turn your ideas into real projects? If your web development skills are a bit rusty, or if you've simply never programmed before, The PHP Workshop will show you how to build dynamic websites using PHP with the help of engaging examples and challenging activities.
This PHP tutorial starts with an introduction to PHP, getting you set up with a productive development environment. You will write, execute, and troubleshoot your first PHP script using a built-in templating engine and server. Next, you'll learn about variables and data types, and see how conditions and loops help control the flow of a PHP program. Progressing through the chapters, you'll use HTTP methods to turn your PHP scripts into web apps, persist data by connecting to an external database, handle application errors, and improve functionality by using third-party packages.
By the end of this Workshop, you'll be well-versed in web application development, and have the knowledge and skills to creatively tackle your own ambitious projects with PHP.
About the Chapters
Chapter 1, Introducing PHP, introduces you to the PHP language, enabling you to set up your first development environment and write your first PHP scripts.
Chapter 2, Types and Operators, introduces the different types used in PHP programming.
Chapter 3, Control Statements, defines different branching and looping techniques and scenarios for the use of different control structures and conditions with operators.
Chapter 4, Functions, looks at functions and the difference between built-in functions and custom functions, as well as exploring the callback function.
Chapter 5, Object-Oriented Programming, explains everything you need to know to have a solid foundational knowledge of object-oriented programming for PHP. You will learn about interfaces, classes, namespaces, class instantiation, class field scopes, methods, magic methods, abstraction, inheritance, object composition, autoloading, and more.
Chapter 6, Using HTTP, explores HTTP requests, which are vital to understand and use in practical web applications. You will become familiar with request types and URL components, find out about common vulnerabilities on the World Wide Web and learn how to protect your application against attacks that exploit those vulnerabilities.
Chapter 7, Data Persistence, describes the utilization of databases, including coverage of their configuration and read and write operations.
Chapter 8, Error Handling, explains error levels and exceptions in PHP, including when they trigger, how they can be triggered, and also—very importantly—how to handle them when they occur.
Chapter 9, Composer, explains how to use the Composer dependency management tool and how to autoload dependencies into PHP scripts.
Chapter 10, Web Services, defines the ways of talking between different platforms by exchanging data.
Note
You can find the bonus chapter, PHPUnit, at: http://packt.live/3tTfEAe.
Conventions
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
The echo construct is one way to print to the screen.
Words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this: Open Insomnia and click on the New Request button.
A block of code is set as follows:
$language = PHP
;
$version = 7.3;
echo $language;
echo $version;
?>
New terms and important words are shown like this: Welcome to the world of Hypertext Preprocessor (PHP).
Long code snippets are truncated and the corresponding names of the code files on GitHub are placed at the top of the truncated code. The permalinks to the entire code are placed below the code snippet. It should look as follows:
Example1.01.php
1
2 en>
3
4 UTF-8>
5 viewport content=width=device-width, initial-scale=1.0
>
6 X-UA-Compatible content=ie=edge
>
7
8
https://packt.live/326OLKU
Before You Begin
Each great journey begins with a humble step. Our upcoming adventure in the land of PHP is no exception. Before we can do awesome things with data, we need to be prepared with a productive environment. In this section, we shall see how to do that.
Installing PHP 7.3 (Ubuntu)
All the exercises in this book were run with PHP 7.3 on Linux Ubuntu 18.10. Since PHP is cross-platform, you can use it on Windows version 7+ (Visual Studio 2015 required) and macOS as well.
Ubuntu 18.04 LTS ships with PHP 7.2 by default, so in order to install the latest stable PHP version, you should compile from source or install precompiled packages on your machine. Installing precompiled packages from trusted sources is often preferred since the time for installation is much lower than that for compiling from source code. In your Terminal, run the following (one line at a time, with superuser privileges):
apt-get update
apt-get install -y software-properties-common
LC_ALL=C.UTF-8 add-apt-repository -y ppa:ondrej/php
apt-get update
apt-get install -y php7.3-common php7.3-curl php7.3-mbstring php7.3-mysql
Installing PHP 7.3 (Mac OS X)
PHP 7.3 can be installed easily using Liip's php-osx tool:
curl -s https://php-osx.liip.ch/install.sh | bash -s 7.3
Or, if you prefer using Homebrew:
brew install php@7.3
Note
To install Homebrew just run /usr/bin/ruby -e $(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)
Installing PHP 7.3 (Windows)
Here are the steps to install PHP 7.3 on a Windows system:
Download the latest PHP 7 (non-thread safe version) ZIP file from https://windows.php.net/download/:
Figure 0.1: Downloading PHP 7Figure 0.1: Downloading PHP 7
Extract the contents of the ZIP file into C:\PHP7.
Copy the C:\PHP7\php.ini-development file to C:\PHP7\php.ini.
Open the newly copied C:\PHP7\php.ini file in a text editor, such as Notepad++, Atom, or Sublime Text.
Change memory_limit from 128M to 1G (to allow for the memory requirements of Composer).
Search for extension_dir and uncomment the line (remove the leading semicolon, so the line will look like extension_dir = ext
).
To add C:\PHP7 to the Windows 10 system path environment variable, open the Control Panel and click on View advanced system settings:
Figure 0.2: Checking for advanced system settingsFigure 0.2: Checking for advanced system settings
Click the Environment Variables… button:
Figure 0.3: Checking environment variablesFigure 0.3: Checking environment variables
Click on the Path row under System variables, and then click on Edit…:
Figure 0.4: Editing the variableFigure 0.4: Editing the variable
Click New and add the C:\PHP7 row:
Figure 0.5: Adding a new rowFigure 0.5: Adding a new row
Click OK for all opened windows so far and close the Control Panel.
In a Command Prompt (PowerShell or another Terminal), test that the installation is successful by typing php -v:
Figure 0.6: Testing the installationFigure 0.6: Testing the installation
Installing MySQL 5.7 (Ubuntu)
To install MySQL 5.7 on your system, run the following in your Terminal:
apt-get update
apt-get install -y mysql-server
Accessing MySQL as Root (Using sudo)
To access MySQL as a root user, run the following command in your Terminal:
sudo mysql --user=root
Creating a Test User
To create a test user, run the following command in the MySQL Terminal:
create user 'php-user'@'%' identified by 'php-pass';
Granting all Privileges on a Test User
To grant all privileges to a test user, run the following command in your Terminal:
grant all on *.* to 'php-user'@'%';
flush privileges;
In a production environment, you would carefully pick the required-by-the-app privileges only, restricting the range of privileges as much as possible. For more information about privileges on MySQL servers, visit https://dev.mysql.com/doc/refman/5.7/en/privileges-provided.html.
Installing MySQL Workbench on Ubuntu
Open the software manager, search for MySQL Workbench, and click on the Install button.
Installing MySQL 5.7 (Mac OS)
To install MySQL 5.7 using Homebrew, run the following command in your Terminal:
brew install mysql@5.7
Make MySQL run always as a service:
brew services start mysql@5.7
Repeat the Accessing MySQL as Root
, Creating a Test User
and Granting all Privileges on a Test User
steps from Linux installation above, in order to add the test user.
Installing MySQL Workbench on Mac OS
Here are the steps to install MySQL workbench on the Mac OS:
Access https://dev.mysql.com/downloads/workbench/.
Pick your operating system (macOS) and download the DMG file. For older Mac OS versions consider clicking on Looking for the latest GA version?
on the right-sided box.
Double-click the downloaded file. You will be presented with the installation window shown in the following figure:
Figure 0.7 MySQL Workbench macOS Installation WindowFigure 0.7 MySQL Workbench macOS Installation Window
Drag the MySQL Workbench icon onto the Applications icon as instructed. MySQL Workbench is now installed, and you can launch it from the Applications folder.
Installing MySQL 5.7 (Windows)
Install MySQL 5.7 on Windows as follows:
Access https://dev.mysql.com/downloads/installer/.
Click on the Looking for previous GA versions? link from the following download box:
Figure 0.8: MySQL installerFigure 0.8: MySQL installer
Pick the latest 5.7 version for Windows and click on the Download button:
Figure 0.9: Downloading the appropriate versionFigure 0.9: Downloading the appropriate version
Run the downloaded file in order to install the MySQL Workbench.
Pick Developer Default (includes the MySQL Workbench as well) and click Next:
Figure 0.10: Selecting the appropriate Setup TypeFigure 0.10: Selecting the appropriate Setup Type
Click Execute to install the dependencies, and then click Next.
Click on Execute to start the download and install the selected components (click on Try again if the download or installation fails):
Figure 0.11: Installing the selected componentsFigure 0.11: Installing the selected components
Click Next and Finish until you come to the MySQL Configuration window Account and Roles prompt; enter a root user password.
Click on the Add User button and enter php_user for the username and php-pass for the password (the same as the details entered when creating the user earlier), and click OK:
Figure 0.12: Entering the credentialsFigure 0.12: Entering the credentials
Note
For Windows OS, the database username php-user in code snippets for Chapter 7, Data Persistence will need to be replaced with php_user. This is because the Windows installer for MySQL does not allow hyphens in usernames.
Hit Next and Execute until the installation process is complete.
Installing Composer
To install Composer on Ubuntu or Mac, you will need to go to https://getcomposer.org/download/ and run the four PHP commands under the Command-line installation section in the given link. There is an encryption code included in the commands to verify the download for security purposes. For example, the commands, at the time of writing, are included as follows (ensure you use the hash value generated for you, not the one shown below):
php -r copy('https://getcomposer.org/installer', 'composer-setup.php');
php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd061569
8a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r unlink('composer-setup.php');
On Windows, you can just download the installer file from https://getcomposer.org/Composer-Setup.exe.
Installing the Insomnia REST Client
Browse to https://insomnia.rest/download/ and download the installer file appropriate for your operating system. Open the installer and complete the installation wizard by selecting the default options.
If you prefer the command line, you can install the Client on Ubuntu using sudo snap install insomnia command, or brew cask install insomnia for macOS.
Installing the Code Bundle
Download the code files from GitHub at https://github.com/PacktWorkshops/The-PHP-Workshop and place them in a new folder called C:\Code. Refer to these code files for the complete code bundle.
If you have any issues or questions about installation, please email us at workshops@packt.com.
1. Introducing PHP
Overview
By the end of this chapter, you will be able to work with PHP's built-in templating engine; write simple HTML files; run a PHP script from the command line; create and assign variables to print simple messages on the web browser; and run PHP's built-in web server on your machine.
Introduction
Welcome to the world of Hypertext Preprocessor (PHP). PHP is a popular programming language that's used all over the internet to create web pages/websites and applications. A web page is a single page, while multiple web pages together are commonly referred to as a website or web application. PHP powers sites such as Facebook, Wikipedia, and WordPress.
PHP was created as a scripting language to allow rich dynamic content (content can come from other PHP pages or can be dynamic in nature and come from external sources such as a database). PHP is an interpreted language, which means you do not have to compile it and create an executable file. Instead, PHP files are interpreted line by line by the web server running PHP.
Compiled languages cannot run directly after each change. Instead, they require an interpreter to compile the code into a program that can be executed. Interpreted languages, on the other hand, can be reloaded as soon as there is a change in the code, allowing for changes to be seen quickly.
PHP is used along with HTML, JavaScript, and CSS to create dynamic web applications. Since PHP is easy to learn, it has a huge developer community around the world. This has led to more and more developers releasing open source projects, frameworks, and resources. For instance, PHP Framework Interop Group, otherwise known as PHP-FIG, (https://packt.live/2oJ0FvY) has created a series of standard recommendations that most developers use to write their code. GitHub houses many open source projects for others to use, and sites such as https://packt.live/2oaK3gt have many videos on web development.
Getting Started with PHP Web Development
PHP is a server-side scripting language. Server-side scripting is a way that web servers can respond to client requests via HTTP. The way this works is that a client (a browser) requests a URL. This request is then sent by a web server to a script. The script then reads this request and, depending on the code in the script, returns the contents of a page.
This process happens every time a web page is visited. When working with forms, data is sent from the client to the server. The data is processed and a response is returned. A common example is that on Facebook, you enter a status update and press Enter. The text is sent via a POST request to the server, checked by the scripts on the server, and then saved to a database. The web page is then updated with the new post. PHP sites can also be API services, which may be called either from JavaScript scripts (as AJAX calls, for instance) or from other services. In those and similar cases, there is no browser request involved.
The following tools are needed for web development:
A browser such as Google Chrome, Firefox, or Microsoft Edge.
A text editor such as Microsoft Visual Studio Code, or an Integrated Development Environment (IDE) such as PHP Storm.
A server to run PHP Apache or NGINX can be used, as well as PHP's built-in server.
Built-in Templating Engine
PHP was created to write applications for the web. It can be written alongside HTML to create dynamic pages. We will see examples of this in a moment.
A PHP templating engine is a way to allow PHP code to output its content alongside HTML content. This gives flexibility to pages. Any page intended to use PHP code has a .php extension instead of an .html extension. This informs the web server to expect PHP content.
A PHP file has a .php extension, and it can contain HTML, JavaScript, and CSS, along with PHP. Since the PHP interpreter needs to know where the code is placed in a PHP file, PHP code is written between two special tags (). These tags are called opening and closing tags. A typical PHP file looks like this:
Example1.01.php
1
2 en>
3
4 UTF-8>
5 viewport content=width=device-width, initial-scale=1.0
>
6 X-UA-Compatible content=ie=edge
>
7
8
9
10
11 The Heading
12
13
14 // your php code goes here
15 ?>
https://packt.live/326OLKU
This page starts off with HTML declaring the doctype, which tells the browser to expect HTML content, followed by meta tags that inform the browser to expect UTF-8 content and a meta tag to use the latest rendering engine and zooming levels.
Note
HTML is covered in detail later in the chapter.
Alternatively, short open tags are also available in PHP, but they are turned off by default. This can be changed by editing a .phpini configuration file when using Apache (this goes beyond the scope of this introduction). Short codes look like this:
// php code here
?>
In short, opening and closing tags inform the PHP interpreter when to start and stop interpreting the PHP code line by line.
Since PHP is a useful web development tool, you will often be working in the browser. However, you will also need to be familiar with the interactive shell.
PHP in the Interactive Shell
Interactive shells are known by a few different names. On Windows, they are referred to as Command Prompt. On Linux/Mac, Terminal is the name given to the computer application that allows commands to be issued and understood by the shell and picked up by PHP.
The interactive shell allows a PHP script to run without a browser. This is how scripts are commonly executed on a server.
Exercise 1.1: Printing Hello World to the Standard Output
In this exercise, we will print a simple statement using the interactive shell. The interactive shell can be used to execute PHP code and/or scripts. Before we begin, ensure that you have followed the installation steps in the preface. Follow these steps to complete the exercise:
Open a Terminal/Command Prompt on your machine.
Write the following command to start PHP's interactive shell and hit Enter:
php -a
You will obtain the following output:
Figure 1.1: Getting started with the interactive shellFigure 1.1: Getting started with the interactive shell
Interactive shell will appear on the prompt, and it changes to php >. Now, you've entered in PHP's interactive shell and can run PHP code and execute scripts. We will explore more interactive shells in upcoming exercises.
Write the following command:
echo Hello World!
;
We will shortly explain what echo means. Once you hit Enter, you will see Hello World! printed on the shell, as shown in the following screenshot:
Figure 1.2: Printing output to the consoleFigure 1.2: Printing output to the console
Congratulations! You have executed your first PHP code.
echo is a PHP construct that prints anything passed to it. In the exercise, we passed Hello World!. Since Hello World! is a string, we have double quotes wrapped around it. You can use echo to print strings, variables, and other things.
The echo construct is one way to print to the screen. Another way is to use print('Hello world!'). While this will display the string passed to it, the main difference between echo and print is that print only accepts a single argument.
There are also functions that look inside a variable, such as print_r($item). This will output the value of any variable passed to the function. This should not be used to display a message to the screen, but instead it should be used when you need to know the contents of a variable.
One important thing to note here is the semicolon at the end of the line. In PHP, the semicolon is mandatory at the end of each statement. PHP will throw an error if a statement does not end with a semicolon.
By now, you should have got the idea that we can execute basic statements in the interactive shell. We will try some more of these later in this chapter. All the functions that we can execute in PHP scripts can be executed from the interactive shell.
Now, we will run a PHP file to output Hello World rather than coding directly using the shell.
Exercise 1.2: Printing Hello World by Executing a PHP File
By now, you have learned how to use the echo statement. Let's now go ahead and create your first PHP script. We will print the same statement as before, but we will use a PHP file this time. Follow these steps:
Create a folder named book on your machine. Create another folder inside it named chapter1. It is recommended that you follow this approach for further chapters as well.
Create a file named hello.php inside the chapter1 folder.
Open the hello.php file using a code editor such as Visual Studio Code or Sublime Text.
Write the following code in hello.php and save it:
echo Hello World!
;
?>
Now, open the Terminal and move to the chapter1 folder. Use cd followed by the folder name to move into the folder. To go up a folder, use ../.
Run the following command in Command Prompt:
php hello.php
You will see Hello World! printed on the screen, just like in the following screenshot:
Figure 1.3: Printing output to the TerminalFigure 1.3: Printing output to the Terminal
First, we have PHP's opening tag. The PHP interpreter will start processing lines one by one after it. The only line of code we have here is the echo statement to which we are passing the Hello World! string. The PHP interpreter processes it and then this string is printed on the Terminal.
All PHP files will be written like this. Some will have HTML and other code, while some may not. Also, remember that there can be multiple opening and closing tags in a single file. These can be placed anywhere in the file.
So, you've learned how to use the interactive shell and how to print simple strings using the echo statement. We will now learn about creating and using variables in PHP.
Assigning and Using Variables
Just as with any other programming language, variables in PHP are used to store data. A key point of difference is that all variable names in PHP must start with the dollar sign, $.
Variables must start with a letter. They cannot start with a number or symbol, but they can contain numbers and symbols.
Data stored in variables can be of the following types:
Integer – whole numbers
Boolean – true or false
Float – floating-point number
String – letters and numbers
The data that is stored in a variable is called the value of the variable.
Creating and Assigning Variables to Print Simple Messages on the Web Browser
Consider the following example, in which we are assigning a value to a variable:
$movieName = Avengers: Endgame
;
?>
Here, a variable named $movieName has been created, and its value is the string Avengers: Endgame
. Since the value is a string, double or single quotes are required around it. = is called the assignment operator. The code basically translates to the following: Assign the value on the right-hand side of the assignment operator to the variable on the left-hand side.
Here are some more examples of creating variables:
$language = PHP
;
$version = 7.3;
echo $language;
echo $version;
?>
If you run the preceding script, you will see PHP7.3 printed. Earlier, we were directly printing values using the echo statement, but now we have assigned the values to a variable. The value is now stored in the variable. One other thing to note is that since 7.3 is a number, it does not need quotation marks.
Suppose you have PHP
written 50 times on a page. If you had to change it to JavaScript,
you would have to replace it in all 50 places. But if the same text, PHP
, is assigned to a variable, you only need to change it once and the change will be reflected everywhere.
There are some rules that must be followed while creating variables:
All variable names in PHP must start with the dollar sign ($).
A variable name cannot start with a number. It must be either a letter or an underscore. For example, $1name and $@name are not valid variable names.
Only A-z, 0-9, and _ are allowed in variable names.
Variable names are case sensitive; for example, $name and $NAME are different.
Variable names must be chosen thoughtfully. They should make sense to someone else reading the code. For example, in an application, if you have to create a variable that stores a user's bank balance, a variable name such as $customerBalance is far more obvious than $xyz.
Unlike languages such as Java and .NET, PHP does not need to declare variables before using them. This means you can just create a variable whenever it's needed, although it's considered a best practice where possible to define your variables at the top of your scripts to make it clear their intent.
PHP also has what are called predefined variables. These are provided by PHP and are available to use by anyone.
One such variable is $argv. This is a list of arguments passed through the Terminal by a script. Rather than executing the script on its own, you can pass values to a script that will be available to use in the $argv variable.
Exercise 1.3: Using Input Variables to Print Simple Strings
In this exercise, we will alter the script from the previous exercise and use the input variables to print strings. Follow these steps:
Reopen the hello.php file using your favorite code editor.
Replace the code with the following code and save the file:
$name = $argv[1];
echo Hello
. $name
?>
Don't worry about the syntax at the moment.
Now, go to the Terminal inside the chapter1 folder.
Run the following command:
php hello.php packt
You will see the following output on the Terminal:
Figure 1.4: Printing output to the consoleFigure 1.4: Printing output to the console
What just happened? The hello.php script printed the value you passed to it. Let's examine how it worked.
You passed the value packt through the command line. This is called passing arguments. You can send multiple arguments shared by a space and these will all be available to the PHP script. But how?
Here comes $argv. $argv is a predefined variable, and once you execute a script, it gets filled with the values passed by the use. It is a list of values after the php keyword on the Terminal. If no arguments are passed, the list only contains the filename. In our case, the list will have two values: hello.php and packt.
Coming back to the script, in the first line of code, we are assigning a value to the $name variable. What is this value? $argv is an array (more about that in later chapters, but basically, an array is a list of things) containing two values. With arrays, the counting begins from 0 instead of 1. So, the first value in $argv is hello.php, which can be taken out using $argv[0]. We need the second value (must be character variables), hence we used $argv[1]. Now, the packt argument passed to the file is stored in the $name variable.
In the second line, we are concatenating the text Hello and the $name variable. The dot operator (.) is used to concatenate multiple values. After concatenation, the string becomes Hello packt, which is then printed by the echo statement.
Note
You can read about more predefined variables and their usage at https://packt.live/2nYJCWN.
You can use either single or double quotes for strings. However, there is a difference between them. You can use variables inside double-quoted strings, and they will be parsed. By this I mean that the value of the variable will be executed rather than simply displaying the name of the variable. On the other hand, single quotes do not do any additional parsing and display the content between the quotes as it is. For this reason, single quotes are slightly faster, and it is recommended to use them.
In the last exercise, we saw how to use the predefined $argv variable. We will use one more predefined variable in this exercise called $_GET. This allows information to be passed to the address bar, and PHP can read it. They are known as query strings
Query strings are key-value pairs that are separated by an ampersand (&). So, ?a=1&b=2 is also a valid query string.