Learning PHP 7 - Antonio Lopez - E-Book

Learning PHP 7 E-Book

Antonio Lopez

0,0
43,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learn the art of PHP programming through this example-rich book filled to the brim with tutorials every PHP developer needs to know

About This Book

  • Set up the PHP environment and get started with web programming
  • Leverage the potential of PHP for server-side programming, memory management, and object-oriented programming (OOP)
  • This book is packed with real-life examples to help you implement the concepts as you learn

Who This Book Is For

If you are a web developer or programmer who wants to create real-life web applications using PHP 7, or a beginner who wants to get started with PHP 7 programming, this book is for you. Prior knowledge of PHP, PHP 7, or programming is not mandatory.

What You Will Learn

  • Set up a server on your machine with PHP
  • Use PHP syntax with the built-in server to create apps
  • Apply the OOP paradigm to PHP to write richer code
  • Use MySQL to manage data in your web applications
  • Create a web application from scratch using MVC
  • Add tests to your web application and write testable code
  • Use an existing PHP framework to build and manage your applications
  • Build REST APIs for your PHP applications
  • Test the behavior of web applications with Behat

In Detail

PHP is a great language for building web applications. It is essentially a server-side scripting language that is also used for general purpose programming. PHP 7 is the latest version with a host of new features, and it provides major backwards-compatibility breaks.

This book begins with the fundamentals of PHP programming by covering the basic concepts such as variables, functions, class, and objects. You will set up PHP server on your machine and learn to read and write procedural PHP code. After getting an understanding of OOP as a paradigm, you will execute MySQL queries on your database. Moving on, you will find out how to use MVC to create applications from scratch and add tests. Then, you will build REST APIs and perform behavioral tests on your applications.

By the end of the book, you will have the skills required to read and write files, debug, test, and work with MySQL.

Style and approach

This book begins with the basics that all PHP developers use every day and then dives deep into detailed concepts and tricks to help you speed through development. You will be able to learn the concepts by performing practical tasks and implementing them in your daily activities, all at your own pace.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 547

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning PHP 7
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Setting Up the Environment
Setting up the environment with Vagrant
Introducing Vagrant
Installing Vagrant
Using Vagrant
Setting up the environment on OS X
Installing PHP
Installing MySQL
Installing Nginx
Installing Composer
Setting up the environment on Windows
Installing PHP
Installing MySQL
Installing Nginx
Installing Composer
Setting up the environment on Ubuntu
Installing PHP
Installing MySQL
Installing Nginx
Summary
2. Web Applications with PHP
The HTTP protocol
A simple example
Parts of the message
URL
The HTTP method
Body
Headers
The status code
A more complex example
Web applications
HTML, CSS, and JavaScript
Web servers
How they work
The PHP built-in server
Putting things together
Summary
3. Understanding PHP Basics
PHP files
Variables
Data types
Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Incrementing and decrementing operators
Operator precedence
Working with strings
Arrays
Initializing arrays
Populating arrays
Accessing arrays
The empty and isset functions
Searching for elements in an array
Ordering arrays
Other array functions
PHP in web applications
Getting information from the user
HTML forms
Persisting data with cookies
Other superglobals
Control structures
Conditionals
Switch…case
Loops
While
Do…while
For
Foreach
Functions
Function declaration
Function arguments
The return statement
Type hinting and return types
The filesystem
Reading files
Writing files
Other filesystem functions
Summary
4. Creating Clean Code with OOP
Classes and objects
Class properties
Class methods
Class constructors
Magic methods
Properties and methods visibility
Encapsulation
Static properties and methods
Namespaces
Autoloading classes
Using the __autoload function
Using the spl_autoload_register function
Inheritance
Introducing inheritance
Overriding methods
Abstract classes
Interfaces
Polymorphism
Traits
Handling exceptions
The try…catch block
The finally block
Catching different types of exceptions
Design patterns
Factory
Singleton
Anonymous functions
Summary
5. Using Databases
Introducing databases
MySQL
Schemas and tables
Understanding schemas
Database data types
Numeric data types
String data types
List of values
Date and time data types
Managing tables
Keys and constraints
Primary keys
Foreign keys
Unique keys
Indexes
Inserting data
Querying data
Using PDO
Connecting to the database
Performing queries
Prepared statements
Joining tables
Grouping queries
Updating and deleting data
Updating data
Foreign key behaviors
Deleting data
Working with transactions
Summary
6. Adapting to MVC
The MVC pattern
Using Composer
Managing dependencies
Autoloader with PSR-4
Adding metadata
The index.php file
Working with requests
The request object
Filtering parameters from requests
Mapping routes to controllers
The router
URLs matching with regular expressions
Extracting the arguments of the URL
Executing the controller
M for model
The customer model
The book model
The sales model
V for view
Introduction to Twig
The book view
Layouts and blocks
Paginated book list
The sales view
The error template
The login template
C for controller
The error controller
The login controller
The book controller
Borrowing books
The sales controller
Dependency injection
Why is dependency injection necessary?
Implementing our own dependency injector
Summary
7. Testing Web Applications
The necessity for tests
Types of tests
Unit tests and code coverage
Integrating PHPUnit
The phpunit.xml file
Your first test
Running tests
Writing unit tests
The start and end of a test
Assertions
Expecting exceptions
Data providers
Testing with doubles
Injecting models with DI
Customizing TestCase
Using mocks
Database testing
Test-driven development
Theory versus practice
Summary
8. Using Existing PHP Frameworks
Reviewing frameworks
The purpose of frameworks
The main parts of a framework
Other features of frameworks
Authentication and roles
ORM
Cache
Internationalization
Types of frameworks
Complete and robust frameworks
Lightweight and flexible frameworks
An overview of famous frameworks
Symfony 2
Zend Framework 2
Other frameworks
The Laravel framework
Installation
Project setup
Adding the first endpoint
Managing users
User registration
User login
Protected routes
Setting up relationships in models
Creating complex controllers
Adding tests
The Silex microframework
Installation
Project setup
Managing configuration
Setting the template engine
Adding a logger
Adding the first endpoint
Accessing the database
Silex versus Laravel
Summary
9. Building REST APIs
Introducing APIs
Introducing REST APIs
The foundations of REST APIs
HTTP request methods
GET
POST and PUT
DELETE
Status codes in responses
2xx – success
3xx – redirection
4xx – client error
5xx – server error
REST API security
Basic access authentication
OAuth 2.0
Using third-party APIs
Getting the application's credentials
Setting up the application
Requesting an access token
Fetching tweets
The toolkit of the REST API developer
Testing APIs with browsers
Testing APIs using the command line
Best practices with REST APIs
Consistency in your endpoints
Document as much as you can
Filters and pagination
API versioning
Using HTTP cache
Creating a REST API with Laravel
Setting OAuth2 authentication
Installing OAuth2Server
Setting up the database
Enabling client-credentials authentication
Requesting an access token
Preparing the database
Setting up the models
Designing endpoints
Adding the controllers
Testing your REST APIs
Summary
10. Behavioral Testing
Behavior-driven development
Introducing continuous integration
Unit tests versus acceptance tests
TDD versus BDD
Business writing tests
BDD with Behat
Introducing the Gherkin language
Defining scenarios
Writing Given-When-Then test cases
Reusing parts of scenarios
Writing step definitions
The parameterization of steps
Running feature tests
Testing with a browser using Mink
Types of web drivers
Installing Mink with Goutte
Interaction with the browser
Summary
Index

Learning PHP 7

Learning PHP 7

Copyright © 2016 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 author, 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.

First published: March 2016

Production reference: 1210316

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-054-4

www.packtpub.com

Credits

Author

Antonio Lopez

Reviewer

Brad Bonkoski

Commissioning Editor

Kunal Parikh

Acquisition Editors

Nikhil Karkal

Divya Poojari

Content Development Editor

Rohit Kumar Singh

Technical Editor

Taabish Khan

Copy Editors

Shruti Iyer

Sonia Mathur

Project Coordinator

Izzat Contractor

Proofreader

Safis Editing

Indexer

Tejal Daruwale Soni

Production Coordinator

Melwyn D'sa

Cover Work

Melwyn D'sa

About the Author

Antonio Lopez is a software engineer with more than 7 years of experience. He has worked with PHP since university, which was 10 years ago, building small personal projects. Later, Antonio started his journey around Europe, working in Barcelona, London, Dublin, and back in Barcelona. He has worked in a number of different areas, from web applications to REST APIs and internal tools. Antonio likes to spend his spare time on personal projects and start-ups and has a strong vocation in education and teaching.

I would like to give thanks to my wife, Neri, for supporting me through the whole process of writing this book without going crazy.

About the Reviewer

Brad Bonkoski has been developing software for over 15 years, specializing in internal operations, systems, tools, and automation. Sometimes, this role is loosely referred to as DevOps. He leans more toward the Dev side of this misunderstood buzzword. After building an incident management system and managing change management for Yahoo, Brad became motivated by metrics and now lives by the mantra that what doesn't get measured doesn't get fixed. Today, he greases the wheels of productivity for Shazam.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

There is no need to state how much weight web applications have in our lives. We use web applications to know what our friends are doing, to get the latest news about politics, to check the results of our favorite football team in a game, or graduate from an online university. And as you are holding this book, you already know that building these applications is not a job that only a selected group of geniuses can perform, and that it's rather the opposite.

There isn't only one way to build web applications; there are actually quite a lot of languages and technologies with the sole purpose of doing this. However, if there is one language that stands out from the rest, either historically or because it is extremely easy to use, it is PHP and all the tools of its ecosystem.

The Internet is full of resources that detail how to use PHP, so why bother reading this book? That's easy. We will not give you the full documentation of PHP as the official website does. Our goal is not that you get a PHP certification, but rather to teach you what you really need in order to build web applications by yourself. From the very beginning, we will use all the information provided in order to build applications, so you can note why each piece of information is useful.

However, we will not stop here. Not only will we show you what the language offers you, but also we will discuss the best approaches to writing code. You will learn all the techniques that any web developer has to master, from OOP and design patterns such as MVC, to testing. You will even work with the existing PHP frameworks that big and small companies use for their own projects.

In short, you will start a journey in which you will learn how to master web development rather than how to master a programming language. We hope you enjoy it.

What this book covers

Chapter 1, Setting Up the Environment, will guide you through the installation of the different software needed.

Chapter 2, Web Applications with PHP, will be an introduction to what web applications are and how they work internally.

Chapter 3, Understanding PHP Basics, will go through the basic elements of the PHP language—from variables to control structures.

Chapter 4, Creating Clean Code with OOP, will describe how to develop web applications following the object-oriented programming paradigm.

Chapter 5, Using Databases, will explain how you can use MySQL databases in your applications.

Chapter 6, Adapting to MVC, will show how to apply the most famous web design pattern, MVC, to your applications.

Chapter 7, Testing Web Applications, will be an extensive introduction to unit testing with PHPUnit.

Chapter 8, Using Existing PHP Frameworks, will introduce you to existing PHP frameworks used by several companies and developers, such as Laravel and Silex.

Chapter 9, Building REST APIs, will explain what REST APIs are, how to use third-party ones, and how to build your own.

Chapter 10, Behavioral Testing, will introduce the concepts of continuous integration and behavioral testing with PHP and Behat.

What you need for this book

In Chapter 1, Setting Up the Environment, we will go through the details of how to install PHP and the rest of tools that you need in order to go though the examples of this book. The only thing that you need to start reading is a computer with Windows, OS X, or Linux, and an Internet connection.

Who this book is for

This book is for anyone who wishes to write web applications with PHP. You do not need to be a computer science graduate in order to understand it. In fact, we will assume that you have no knowledge at all of software development, neither with PHP nor with any other language. We will start from the very beginning so that everybody can follow the book.

Experienced readers can still take advantage of the book. You can quickly review the first chapter in order to discover the new features PHP 7 comes with, and then focus on the chapters that might interest you. You do not need to read the book from start to end, but instead keep it as a guide, in order to refresh specific topics whenever they are needed.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Now, create a myactions.js file with the following content."

A block of code is set as follows:

#special { font-size: 30px; }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<head> <meta charset="UTF-8"> <title>Your first app</title> <link rel="stylesheet" type="text/css" href="mystyle.css"> </head>

Any command-line input or output is written as follows:

$ sudo apt-get update

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Click on Next until the end of the installation wizard."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Setting up the environment on OS X

If you are not convinced with Vagrant and prefer to use a Mac to develop PHP applications, this is your section. Installing all the necessary tools on a Mac might be a bit tricky, depending on the version of your OS X. At the time of writing this book, Oracle has not released a MySQL client that you can use via the command line that works with El Capitan, so we will describe how to install another tool that can do a similar job.

Installing PHP

If it is the first time you are using a Mac to develop applications of any kind, you will have to start by installing Xcode. You can find this application for free on the App Store:

Another indispensable tool for Mac users is Brew. This is the package manager for OS X and will help us install PHP with almost no pain. To install it, run the following command on your command line:

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

If you already have Brew installed, you can make sure that everything works fine by running these two commands:

$ brew doctor$ brew update

It is time to install PHP 7 using Brew. To do so, you will just need to run one command, as follows:

$ brew install homebrew/php/php70

The result should be as shown in the following screenshot:

Make sure to add the binary to your PATH environment variable by executing this command:

$ export PATH="$(brew --prefix homebrew/php/php70)/bin:$PATH"

You can check whether your installation was successful by asking which version of PHP your system is using with the $ php –v command.

Installing MySQL

As pointed out at the beginning of this section, MySQL is a tricky one for Mac users. You need to download the MySQL server installer and MySQL Workbench as the client. The MySQL server installer can be found at https://dev.mysql.com/downloads/mysql/. You should find a list of different options, as shown here:

The easiest way to go is to download DMG Archive. You will be asked to log in with your Oracle account; you can create one if you do not have any. After this, the download will start. As with any DMG package, just double-click on it and go through the options—in this case, just click on Next all the time. Be careful because at the end of the process, you will be prompted with a message similar to this:

Make a note of it; otherwise, you will have to reset the root password. The next one is MySQL Workbench, which you can find at http://www.mysql.com/products/workbench/. The process is the same; you will be asked to log in, and then you will get a DMG file. Click on Next until the end of the installation wizard. Once done, you can launch the application; it should look similar to this:

Installing Nginx

In order to install Nginx, we will use Brew, as we did with PHP. The command is the following:

$ brew install nginx

If you want to make Nginx start every time you start your laptop, run the following command:

$ ln -sfv /usr/local/opt/nginx/*.plist ~/Library/LaunchAgents

If you have to change the configuration of Nginx, you will find the file in /usr/local/etc/nginx/nginx.conf. You can change things, such as the port that Nginx is listening to or the root directory where your code is (the default directory is /usr/local/Cellar/nginx/1.8.1/html/). Remember to restart Nginx to apply the changes with the sudo nginx command.

Installing Composer

Installing Composer is as easy as downloading it with the curl command; move the binary to /usr/local/bin/ with the following two commands:

$ curl -sS https://getcomposer.org/installer | php$ mv composer.phar /usr/local/bin/composer

Setting up the environment on Windows

Even though it is not very professional to pick sides based on personal opinions, it is well known among developers how hard it can be to use Windows as a developer machine. They prove to be extremely tricky when it comes to installing all the software since the installation mode is always very different from OS X and Linux systems, and quite often, there are dependency or configuration problems. In addition, the command line has different interpreters than Unix systems, which makes things a bit more confusing. This is why most developers would recommend you use a virtual machine with Linux if you only have a Windows machine at your disposal.

However, to be fair, PHP 7 is the exception to the rule. It is surprisingly simple to install it, so if you are really comfortable with your Windows and would prefer not to use Vagrant, here you have a short explanation on how to set up your environment.

Installing PHP

In order to install PHP 7, you will first download the installer from the official website. For this, go to http://windows.php.net/download. The options should be similar to the following screenshot:

Choosex86 Thread Safe for Windows 32-bit or x64 Thread Safe for the 64-bit one. Once downloaded, uncompress it in C:\php7. Yes, that is it!

Installing MySQL

Installing MySQL is a little more complex. Download the installer from http://dev.mysql.com/downloads/installer/ and execute it. After accepting the license agreement, you will get a window similar to the following one:

For the purposes of the book—and actually for any development environment—you should go for the first option: Developer Default. Keep going forward, leaving all the default options, until you get a window similar to this:

Depending on your preferences, you can either just set a password for the root user, which is enough as it is only a development machine, or you can add an extra user by clicking on Add User. Make sure to set the correct name, password, and permissions. A user named test with administration permissions should look similar to the following screenshot:

For the rest of the installation process, you can select all the default options.

Installing Nginx

The installation for Nginx is almost identical to the PHP 7 one. First, download the ZIP file from http://nginx.org/en/download.html. At the time of writing, the versions available are as follows:

You can safely download the mainline version 1.9.10 or a later one if it is stable. Once the file is downloaded, uncompress it in C:\nginx and run the following commands to start the web server:

$ cd nginx$ start nginx

Installing Composer

To finish with the setup, we need to install Composer. To go for the automatic installation, just download the installer from https://getcomposer.org/Composer-Setup.exe. Once downloaded, execute it in order to install Composer on your system and to update your PATH environment variable.

Setting up the environment on Ubuntu

Setting up your environment on Ubuntu is the easiest of the three platforms. In fact, you could take the provisioner.sh script from the Setting up the environment with Vagrant section and execute it on your laptop. That should do the trick. However, just in case you already have some of the tools installed or you want to have a sense of control on what is going on, we will detail each step.

Installing PHP

The only thing to consider in this section is to remove any previous PHP versions on your system. To do so, you can run the following command:

$ sudo apt-get -y purge php.*

The next step is to add the necessary repositories in order to fetch the correct PHP version. The commands to add and update them are:

$ sudo apt-get install python-software-properties$ sudo LC_ALL=en_US.UTF-8 add-apt-repository ppa:ondrej/php -y$ sudo apt-get update

Finally, we need to install PHP 7 together with the driver for MySQL. For this, just execute the following three commands:

$ sudo apt-get install php7.0 php7.0-fpm php7.0-mysql -y$ sudo apt-get --purge autoremove -y$ sudo service php7.0-fpm start

Installing MySQL

Installing MySQL manually can be slightly different than with the Vagrant script. As we can interact with the console, we do not have to specify the root password previously; instead, we can force MySQL to prompt for it. Run the following command and keep in mind that the installer will ask you for the password:

$ sudo apt-get -y install mysql-server mysql-client

Once done, if you need to start the MySQL server, you can do it with the following command:

$ sudo service mysql start

Installing Nginx

The first thing that you need to know is that you can only have one web server listening on the same port. As port 80 is the default one for web applications, if you are running Apache on your Ubuntu machine, you will not be able to start an Nginx web server listening on the same port 80. To fix this, you can either change the ports for Nginx or Apache, stop Apache, or uninstall it. Either way, the installation command for Nginx is as follows:

$ sudo apt-get install nginx –y

Now, you will need to enable a site with Nginx. The sites are files under /etc/nginx/sites-available. There is already one file there, default, which you can safely replace with the following content:

server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /var/www/html; index index.php index.html index.htm; server_name server_domain_or_IP; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { try_files $uri /index.php =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }

This configuration basically points the root directory of your web application to the /var/www/html directory. You can choose the one that you prefer, but make sure that it has the right permissions. It also listens on the port 80, which you can change with the one you prefer; just keep this in mind that when you try to access your application via a browser. Finally, to apply all the changes, run the following command:

$ sudo service nginx restart

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Summary

In this chapter, you learned how easy it is to set up a development environment using Vagrant. If this did not convince you, you still got the chance to set up all the tools manually. Either way, now you are able to work on the next chapters.

In the next chapter, we will take a look at the idea of web applications with PHP, going from the protocols used to how the web server serves requests, thus setting the foundation for the following chapters.

Chapter 2. Web Applications with PHP

Web applications are a common thing in our lives, and they are usually very user friendly; users do not need to understand how they work behind the scenes. As a developer, though, you need to understand how your application works internally.

In this chapter, you will learn about:

HTTP and how web applications make use of itWeb applications and how to build a simple oneWeb servers and how to launch your PHP built-in web server

The HTTP protocol

If you check the RFC2068 standard at https://tools.ietf.org/html/rfc2068, you will see that its description is almost endless. Luckily, what you need to know about this protocol, at least for starters, is way shorter.

HTTP stands for HyperText Transfer Protocol. As any other protocol, the goal is to allow two entities or nodes to communicate with each other. In order to achieve this, the messages need to be formatted in a way that they both understand, and the entities must follow some pre-established rules.

A simple example

The following diagram shows a very basic interchange of messages:

A simple GET request

Do not worry if you do not understand all the elements in this diagram; we will describe them shortly. In this representation, there are two entities: sender and receiver. The sender sends a message to the receiver. This message, which starts the communication, is called the request. In this case, the message is a GET request. The receiver receives the message, processes it, and generates a second message: the response. In this case, the response shows a 200 status code, meaning that the request was processed successfully.

HTTP is stateless; that is, it treats each request independently, unrelated to any previous one. This means that with this request and response sequence, the communication is finished. Any new requests will not be aware of this specific interchange of messages.

Parts of the message

An HTTP message contains several parts. We will define only the most important of them.

URL

The URL of the message is the destination of the message. The request will contain the receiver's URL, and the response will contain the sender's.

As you might know, the URL can contain extra parameters, known as a query string. This is used when the sender wants to add extra data. For example, consider this URL: http://myserver.com/greeting?name=Alex. This URL contains one parameter: name with the value Alex. It could not be represented as part of the URL http://myserver.com/greeting, so the sender chose to add it at the end of it. You will see later that this is not the only way that we can add extra information into a message.

The HTTP method

The HTTP method is the verb of the message. It identifies what kind of action the sender wants to perform with this message. The most common ones are GET and POST.

GET: This asks the receiver about something, and the receiver usually sends this information back. The most common example is asking for a web page, where the receiver will respond with the HTML code of the requested page.POST: This means that the sender wants to perform an action that will update the data that the receiver is holding. For example, the sender can ask the receiver to update his profile name.

There are other methods, such as PUT, DELETE, or OPTION, but they are less used in web development, although they play a crucial role in REST APIs, which will be explained in Chapter 9, Building REST APIs.

Body

The body part is usually present in response messages even though a request message can contain it too. The body of the message contains the content of the message itself; for example, if the user requested a web page, the body of the response would consist of the HTML code that represents this page.

Soon, we will discuss how the request can also contain a body, which is used to send extra information as part of the request, such as form parameters.

The body can contain text in any format; it can be an HTML text that represents a web page, plain text, the content of an image, JSON, and so on.

Headers

The headers on an HTTP message are the metadata that the receiver needs in order to understand the content of the message. There are a lot of headers, and you will see some of them in this book.

Headers consist of a map of key-value pairs. The following could be the headers of a request:

Accept: text/html Cookie: name=Richard

This request tells the receiver, which is a server, that it will accept text as HTML, which is the common way of representing a web page; and that it has a cookie named Richard.

The status code

The status code is present in responses. It identifies the status of the request with a numeric code so that browsers and other tools know how to react. For example, if we try to access a URL that does not exist, the server should reply with a status code 404. In this way, the browser knows what happened without even looking at the content of the response.

Common status codes are:

200: The request was successful401: Unauthorized; the user does not have permission to see this resource404: Page not found500: Internal server error; something wrong happened on the server side and it could not be recovered

A more complex example

The following diagram shows a POST request and its response:

A more complex POST request

In this exchange of messages, we can see the other important method, POST, in action. In this case, the sender tries to send a request in order to update some entity's data. The message contains a cookie ID with the value 84, which may identify the entity to update. It also contains two parameters in the body: name and age. This is the data that the receiver has to update.

Tip

Submitting web forms

Representing the parameters as part of the body is a common way to send information when submitting a form, but not the only one. You can add a query string to the URL, add JSON to the body of the message, and so on.

The response has a status code of 200, meaning that the request was processed successfully. In addition, the response also contains a body, this time formatted as JSON, which represents the new status of the updated entity.

Web servers

So, it is about time that you learn what those famous web servers are. A web server is no more than a piece of software running on a machine and listening to requests from a specific port. Usually, this port is 80, but it can be any other that is available.

How they work

The following diagram represents the flow of request-response on the server side:

Request-response flow on the server side

The job of a web server is to route external requests to the correct application so that they can be processed. Once the application returns a response, the web server will send this response to the client. Let's take a close look at all the steps:

The client, which is a browser, sends a request. This can be of any type—GET or POST—and contain anything as long as it is valid.The server receives the request, which points to a port. If there is a web server listening on this port, the web server will then take control of the situation.The web server decides which web application—usually a file in the filesystem—needs to process the request. In order to decide, the web server usually considers the path of the URL; for example, http://myserver.com/app1/hi would try to pass the request to the app1 application, wherever it is in the filesystem. However, another scenario would be http://app1.myserver.com/hi, which would also go to the same application. The rules are very flexible, and it is up to both the web server and the user as to how to set them.The web application, after receiving a request from the web server, generates a response and sends it to the web server.The web server sends the response to the indicated port.The response finally arrives to the client.

The PHP built-in server

There are powerful web servers that support high loads of traffic, such as Apache or Nginx, which are fairly simple to install and manage. For the purpose of this book, though, we will use something even simpler: a PHP built-in server. The reason to use this is that you will not need extra package installations, configurations, and headaches as it comes with PHP. With just one command, you will have a web server running on your machine.

Note

Production web servers

Note that the PHP built-in web server is good for testing purposes, but it is highly recommended not to use it in production environments. If you have to set up a server that needs to be public and your application is written in PHP, I highly recommend you to choose either of the classics: Apache (http://httpd.apache.org) or Nginx (https://www.nginx.com). Both can run almost on any server, are free and easy to install and configure, and, more importantly, have a huge community that will support you on virtually any problem you might encounter.

Finally, hands on! Let's try to create our very first web page using the built-in server. For this, create an index.php file inside your workspace directory—for example, Documents/workspace/index.php. The content of this file should be:

<?php echo 'hello world';

Now, open your command line, go to your workspace directory, probably by running the cd Documents/workspace command, and run the following command:

$ php -S localhost:8000

The command line will prompt you with some information, the most important one being what is listening, which should be localhost:8000 as specified, and how to stop it, usually by pressing Ctrl + C. Do not close the command line as it will stop the web server too.

Now, let's open a browser and go to http://localhost:8000. You should see a hello world message on a white page. Yay, success! If you are interested, you can check your command line, and you will see log entries of each request you are sending via your browser.

So, how does it really work? Well, if you check again in the previous diagram, the php -S command started a web server—in our case, listening to port 8000 instead of 80. Also, PHP knows that the web application code will be on the same directory that you started the web server: your workspace. There are more specific options, but by default, PHP will try to execute the index.php file in your workspace.

Putting things together

Let's try to include our first project (index.html with its CSS and JS files) as part of the built-in server. To do this, you just need to open the command line and go to the directory in which these files are and start the web server with php -S localhost:8000. If you check localhost:8000 in your browser, you will see our two-link page, as is expected.

Let's now move our new index.php file to the same directory. You do not need to restart your web server; PHP will know about the changes automatically. Go to your browser and refresh the page. You should now see the hello world message instead of the links. What happened here?

If you do not change the default options, PHP will always try to find an index.php file in the directory in which you started the web server. If this is not found, PHP will try to find an index.html file. Previously, we only had the index.html file, so PHP failed to find index.php. Now that it can find its first option, index.php, it will load it.

If we want to see our index.html file from the browser, we can always specify it in the URL like http://localhost:8000/index.html. If the web server notices that you are trying to access a specific file, it will try to load it instead of the default options.

Finally, if we try to access a file that is not on our filesystem, the web server will return a response with status code 404—that is, not found. We can see this code if we open the Developer tools section of our browser and go to the Network section.

Tip

Developer tools are your friends

As a web developer, you will find very few tools more useful than the developer tools of your browser. It changes from browser to browser, but all of the big names, such as Chrome or Firefox, have it. It is very important that you get familiar with how to use it as it allows you to debug your applications from the client side.

I will introduce you to some of these tools during the course of this book.

Summary

In this chapter, you learned what HTTP is and how web applications use it in order to interact with the server. You also now know how web servers work and how to launch a light built-in server with PHP. Finally, you took the first steps toward building your first web application. Congratulations!

In the next chapter, we will take a look at the basics of PHP so that you can start building simple applications.

Chapter 3. Understanding PHP Basics

Learning a new language is not easy. You need to understand not only the syntax of the language, but also its grammatical rules, that is, when and why to use each element of the language. Luckily for you, some languages come from the same root. For example, Spanish and French are Romance languages, as they both evolved from spoken Latin; that means that these two languages share a lot of rules, and if you already know French, learning Spanish becomes much easier.

Programming languages are quite the same. If you already know another programming language, it will be very easy for you to go through this chapter. If this is your first time though, you will need to understand all those grammatical rules from scratch, and so, it might take some more time. But fear not! We are here to help you in this endeavor.

In this chapter, you will learn about the following:

PHP filesVariables, strings, arrays, and operators in PHPPHP in web applicationsControl structures in PHPFunctions in PHPThe PHP filesystem

PHP files

From now on, we will work on your index.php file, so you can just start the web server, and go to http://localhost:8080 to see the results.

You might have already noticed that in order to write PHP code, you have to start the file with <?php. There are other options, and you can also finish the file with ?>, but none of them are needed. What is important to know is that you can mix PHP code with other content, like HTML, CSS, or JavaScript, in your PHP file as soon as you enclose the PHP bits with the <?php ?> tags.

<?php echo 'hello world'; ?>bye world

If you check the result of the preceding code snippet in your browser, you will see that it prints both messages, hello world and bye world. The reason why this happens is simple: you already know that the PHP code there prints the hello world message. What happens next is that anything outside the PHP tags will be interpreted as is. If there is an HTML code for instance, it would not be printed as is, but will be interpreted by the browser.

You will learn in Chapter 6, Adapting to MVC, why it is usually a bad idea to mix PHP and HTML. For now, assuming that it is bad, let's try to avoid it. For that, you can include one file from another PHP file using any one of these four functions:

include: This will try to find and include the specified file each time it is invoked. If the file is not found, PHP will throw a warning, but will continue with the execution.require: This will do the same as include, but PHP will throw an error instead of a warning if the file is not found.include_once: This function will do what include does, but it will include the file only the first time that it is invoked. Subsequent calls will be ignored.require_once: This works the same as require, but it will include the file only the first time that it is invoked. Subsequent calls will be ignored.

Each function has its own usage, so it is not right to say that one is better than the other. Just think carefully what your scenario is, and then decide. For example, let's try to include our index.html file from our index.php file such that we do not mix PHP with HTML, but have the best of both worlds:

<?php echo 'hello world'; require 'index.html';

We chose require as we know the file is there—and if it is not, we are not interested in continuing the execution. Moreover, as it is some HTML code, we might want to include it multiple times, so we did not choose the require_once option. You can try to require a file that does not exist, and see what the browser says.

PHP does not consider empty lines; you can add as many as you want to make your code easier to read, and it will not have any repercussion on your application. Another element that helps in writing understandable code, and which is ignored by PHP, is comments. Let's see both in action:

<?php /* * This is the first file loaded by the web server. * It prints some messages and html from other files. */// let's print a message from php echo 'hello world'; // and then include the rest of html require 'index.html';

The code does the same job as the previous one, but now everyone will easily understand what we are trying to do. We can see two types of comments: single-line comments and multiple-line comments. The first type consists of a single line starting with //, and the second type encloses multiple lines within /* and */. We start each commented line with an asterisk, but that is completely optional.