Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
The PHP Workshop
The PHP Workshop

The PHP Workshop: Learn to build interactive applications and kickstart your career as a web developer

Arrow left icon
Profile Icon Busuioc Profile Icon Martinez Profile Icon Tonu Profile Icon McLeod Profile Icon McCollum Profile Icon Joshi Profile Icon Gray Profile Icon Carr +4 more Show less
Arrow right icon
₹799 ₹1965.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (4 Ratings)
eBook Oct 2019 604 pages 1st Edition
eBook
₹799 ₹1965.99
Paperback
₹2457.99
Subscription
Free Trial
Renews at ₹800p/m
Arrow left icon
Profile Icon Busuioc Profile Icon Martinez Profile Icon Tonu Profile Icon McLeod Profile Icon McCollum Profile Icon Joshi Profile Icon Gray Profile Icon Carr +4 more Show less
Arrow right icon
₹799 ₹1965.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (4 Ratings)
eBook Oct 2019 604 pages 1st Edition
eBook
₹799 ₹1965.99
Paperback
₹2457.99
Subscription
Free Trial
Renews at ₹800p/m
eBook
₹799 ₹1965.99
Paperback
₹2457.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

The PHP Workshop

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 (<?php...?>). These tags are called opening and closing tags. A typical PHP file looks like this:

Example1.01.php

1  <!DOCTYPE html>
2  <html lang="en">
3  <head>
4      <meta charset="UTF-8">
5      <meta name="viewport" content="width=device-width, initial-scale=1.0">
6      <meta http-equiv="X-UA-Compatible" content="ie=edge">
7     <title>My First PHP Page</title>
8  </head>
9  <body>
10     <div>
11         <h1>The Heading</h1>
12         <p>
13             <?php
14             // your php code goes here 
15             ?>

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:

  1. Open a Terminal/Command Prompt on your machine.
  2. 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 shell

    Figure 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.

  3. 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 console

Figure 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:

  1. 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.
  2. Create a file named hello.php inside the chapter1 folder.
  3. Open the hello.php file using a code editor such as Visual Studio Code or Sublime Text.
  4. Write the following code in hello.php and save it:
    <?php
    echo "Hello World!";
    ?>
  5. 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 ../.
  6. 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 Terminal

Figure 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:

<?php
$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:

<?php
$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:

  1. Reopen the hello.php file using your favorite code editor.
  2. Replace the code with the following code and save the file:
    <?php
    $name = $argv[1];
    echo "Hello ". $name
    ?>

    Don't worry about the syntax at the moment.

  3. Now, go to the Terminal inside the chapter1 folder.
  4. Run the following command:
    php hello.php packt

    You will see the following output on the Terminal:

Figure 1.4: Printing output to the console

Figure 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.

Exercise 1.4: Using the Built-in Server to Print a String

In this exercise, we will use the built-in server to print Hello Packt using the companyName=Packt query string. This will allow you to start using the browser to view the output of your code, rather than just using the interactive shell. Follow these steps:

  1. Reopen the hello.php file using your favorite code editor.
  2. Replace the code with the following code and save the file:
    <?php
    $name = $_GET['companyName'];
    echo "Hello ". $name;
    ?>
  3. Go to the Terminal and go inside the chapter1 folder.
  4. Run the following command to run PHP's built-in web server:
    php -S localhost:8085
  5. Now, open the browser and enter the following in the address bar and hit Enter:
    http://localhost:8085/hello.php?companyName=Packt

    You will see the following output on your screen:

Figure 1.5: Printing output to the browser

Figure 1.5: Printing output to the browser

This is somewhat like the previous exercise, but rather than using the Terminal, we used the browser.

Notice the URL in the browser. After the filename, we have appended ?companyName=Packt. The ? denotes that what follows is a query string. In our code, a variable named companyName with a value of Packt is being passed to the PHP file.

Coming to the code now, in the first line, we have $_GET['companyName']. $_GET is also a predefined variable that is populated when any PHP string with a query string is executed. So, by using $_GET['companyName'], we will get the value Packt, which will be stored in the $name variable. Remember that you can extract any value from the query string using the respective key.

The next line then combines them and displays the result on the browser.

Now that we have started to use the browser to view the output of our work, let's take a quick look at HTML. As discussed earlier, PHP and HTML are often used hand-in-hand, so an understanding of HTML will prove useful as you become more familiar with PHP.

HyperText Markup Language

HyperText Markup Language (HTML) is a language whose meaning is defined via tags and attributes in a hierarchical way. It is used for creating documents such as web pages on the World Wide Web, which are usually displayed in a web browser. They can include texts, links, pictures, and even sound and video.

HTML uses different tags and attributes to define the layout of a web document such as forms.

A tag is an HTML element enclosed by < and >, such as <body>, <p>, and <br>. It consists of an opening tag and an ending tag, with content in-between. For example, consider the following line of HTML:

<p>A paragraph</p>

The opening tag is <p> and the closing tag is </p>, while the content is A paragraph.

An attribute of the HTML element provides additional information about the element and is described by its name and value and has the following syntax: name[="value"]. Specifying the value is optional. For example, the following hyperlink has an attribute with the name href, and the value /home:

<a href="/home">Home</a>

Any HTML document requires the document type declaration, <!DOCTYPE html>, and the <title> tag, like this:

<!DOCTYPE html><title>The document title</title>

There is a list of optional tags that many developers use to create the structure of an HTML document, which are <html>, <head>, and <body>. The <html> tag is the root tag of the HTML document, which is placed immediately after the document type declaration. It will contain the other two optional tags: <head> and <body>. The <head> tag is used for the page metadata and includes <meta> tags to describe the encoding character set used in document for example, it includes the <title> tag, and external resources, such as styles, fonts, and scripts. The <body> block is used to render its contents in a browser window and includes the largest variety of HTML tags.

The aforementioned HTML tags can be seen in any HTML document.

Here's a list of the most frequently used tags:

  • <div>: This tag defines a section in an HTML document. It is usually used as a wrapper element for other HTML elements.
  • <h1> to <h6>: The heading tags are used to define the heading of the HTML document. <h1> defines the most important headings (they also use the biggest font size), while <h6> defines the least important headings. They can be used anywhere in an HTML document.
  • <p>: The paragraph tag is used to define paragraph content in an HTML document.
  • <em>: The emphasis tag is used to emphasize text.
  • <b> and/or <strong>: The bold tag is used to specify bold content.
  • <a href="..."> Link name </a>: The anchor tag is used to link one page to another page.
  • <ul> and <li>: The unordered list and list item tags are used to list the content without order (like a bulleted list).
  • <ol>: This tag is used to represent a numbered list
  • <br>: The line break tag is used to break the line.
  • <img>: The image tag is used to add an image element to an HTML document.
  • <hr>: The horizontal rule tag is used to display the horizontal line in an HTML document.
  • <table>: The table tag is used to create a table in an HTML document.
  • <tr>: The table row tag is used to define a row in an HTML table.
  • <th>: The table heading cell tag defines the header cell in a table.
  • <td>: The table data cell tag defines the standard cell in a table.
  • <form>: The form tag is used to create an HTML form.
  • <input>: The input tag is used to collect and submit user data (such as forms from a browser).
  • <select> and <option>: The select input tag is used to select an option value from a drop-down list.
  • <label>: The label tag prints the label for a form input.

Consider the following HTML block:

<!DOCTYPE html>
<html lang="en">
<head> 
    <meta charset="utf-8">
    <title>HTML Document Title</title>
</head>
<body>
<h1>Heading Text</h1>
<p>A paragraph</p>
<form method="post">
    <input type="text" name="domain">
    <input type="submit" value="Send">
</form>
</body>
</html>

Let's have a look at the HTML elements in this block:

  • <!DOCTYPE html> declares the document type to HTML5.
  • <html lang="en"> is the opening tag for the root element of the HTML document. The lang attribute is pointing to the document content language.
  • <head> opens the metadata block.
  • <meta charset="utf-8"> declares the character set used in the HTML document.
  • <title>HTML Document Title</title> sets the title to HTML Document Title.
  • <body> opens the HTML document content block.
  • <h1>Heading Text</h1> adds a Heading Text heading.
  • <p>A paragraph</p> adds a paragraph containing the text A paragraph.
  • <form method="post"> opens the form block, declaring the method that will be used to send its data (more about this in Chapter 6, Using HTTP).
  • <input type="text" name="domain"> adds a text input field called domain. The "domain" value is the name of the input type.
  • <input type="submit" value="Send"> adds a submit button with Send on it.
  • </form>, </head>, </body>, and </html> are the closing tags for the <form>, <head>, <body>, and <html> tags.

The preceding code will render the following web page:

Figure 1.6: Layout of the web page

Figure 1.6: Layout of the web page

We can access the file with a GET request. Submitting the form will result in a POST request:

Figure 1.7: Methods used

Figure 1.7: Methods used

Request types and form data submission will be covered in Chapter 6, Using HTTP.

Cascading Style Sheets

Cascading Style Sheets (CSS) is the language for defining the styles of web pages. It is possible to change color, font, and so on using CSS. While the HTML describes the structure of a web page, CSS describes what the page will look like on various devices and screen types.

Nowadays, it is very common to use a CSS framework because it contains some presets to make the web pages compatible across browsers, and offers a number of tools, such as a grid system, to make the creation of page layout easier and to implement responsiveness.

One such framework is Bootstrap, and using it is as simple as including the generated and minified CSS file in the HTML document:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

Including the CSS file in the original HTML document will make the browser render the page a bit differently:

Figure 1.8: Rendering the web page

Figure 1.8: Rendering the web page

As you can see, the font is different, but no other major changes are visible. This is because the CSS rules from the linked file do not match any of the elements to decorate. The Bootstrap documentation (https://packt.live/2N1LHJU) shows what it is capable of. Usually, the class attributes are used to match the target HTML elements. Therefore, by simply adding class="btn btn-primary" to the submit input, we will get the button formatted according to the defined style:

Figure 1.9: Adding CSS to a button

Figure 1.9: Adding CSS to a button

We didn't need to define a single CSS rule. The button was rendered according to the already-defined rules from the Bootstrap framework. If we inspect the submitted input styles in Developer Tools (Chrome), we will see the following cascade that is applied to the HTML element:

Figure 1.10: Inspecting the submit input styles in Developer Tools

Figure 1.10: Inspecting the submit input styles in Developer Tools

Of course, we can create an additional CSS file and link it to the HTML document, overwriting some of the Bootstrap declarations.

Exercise 1.5: Creating a Login Form Page Using Bootstrap

You are required to create a simple login page using the Bootstrap framework. Follow these steps:

  1. Create a file called login-form.html.
  2. Declare the document type as HTML5 and open the root HTML element:
    <!DOCTYPE html>
    <html lang="en">
  3. Add the head block containing the page title, the link to the Bootstrap CSS framework, and the meta tag required by the CSS framework:
    <head>
        <title>Login form</title>
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/      bootstrap.min.css" rel="stylesheet">
        <meta content="width=device-width, initial-scale=1, shrink-to-fit=no"       name="viewport">
    </head>
  4. Open the body element and add the container div, aligning the contents to the center:
    <body>
    <div class="container d-flex justify-content-center">
  5. Open the form element and add the form title – an H1 centered text heading:
        <form method="post">
            <div class="text-center mt-4">
                <h1 class="h3 mb-3 font-weight-normal">Authenticate</h1>
            </div>
  6. Add the first form label and input group for the username:
            <div class="form-label-group mb-3">
                <label for="inputUser">Username</label>
                <input class="form-control" id="inputUser" name="username"               placeholder="Username" type="text">
            </div>
  7. Add the password-related label and input tags:
            <div class="form-label-group mb-3">
                <label for="inputPassword">Password</label>
                <input class="form-control" id="inputPassword" name="password"                placeholder="Password" type="password">
            </div>
  8. Add the button that will submit the form:
            <button class="btn btn-lg btn-primary btn-block"           type="submit">Login</button>
  9. Close all opened tags.

    Note

    The final file can be referred at https://packt.live/2MBLNZx.

    Open the file in the browser. The expected output is as follows:

Figure 1.11: The login page

Figure 1.11: The login page

The form is rendered using the default styles of Bootstrap, which are far richer than the browser's defaults.

In this exercise, you rendered an HTML page, including some of the most widely used HTML elements, such as the form element, and you used the Bootstrap CSS file:

<h1>Hello <?php echo $name; ?></h1>

In this case, the Packt string is stored in the $name variable, and the output Hello Packt will be printed in heading 1 (in the biggest font size).

Note

The file extension will be .php.

This is possible because PHP scans the script file and will only run the code between the opening tag (<?php or <?=) and the closing tag (?>) when the closing tag is present, replacing it with the code output, if any.

Exercise 1.6: Printing PHP Code Output between HTML Tags

In this exercise, we will use the built-in server to print Hello Packt using the companyName=Packt query string. Follow these steps:

  1. Reopen the hello.php file using your favorite code editor.
  2. Replace the code with the following code and save the file:
    <h1><?php echo "Hello ". $_GET['companyName'];?>!</h1>
    <hr>
  3. Now, open the browser and enter the following in the address bar and hit Enter:
    http://localhost:8085/hello.php?companyName=Packt

    You will see the following output on your screen:

Figure 1.12: Printing output to the browser

Figure 1.12: Printing output to the browser

As we can see, PHP has such a degree of flexibility that it allows us to use parts of PHP code inside other types of content.

Let's now have a look at other predefined variables available in PHP.

Using the Server Variable

$_SERVER is an already populated predefined array made available by PHP. It contains information about the server and the environment. The information available in $_SERVER differs from server to server, so the fields may vary depending on the environment.

Exercise 1.7: Displaying Server Information

In this exercise, we will use $_SERVER to print the server information to the browser. Follow these steps:

  1. Go to the chapter1 folder.
  2. Create a new file named server.php in the folder.
  3. Write the following PHP code in the file and save it:
    <?php 
    echo '<pre>';
    print_r($_SERVER);
    echo '</pre>';
    ?>
  4. Open your browser and type the following URL in the address bar:
    http://localhost:8085/server.php

    You will see a screen like the following:

Figure 1.13: Printing details to the browser

Figure 1.13: Printing details to the browser

In the preceding code, we used the print_r statement to print the contents of $_SERVER. Since it is an array containing multiple entries, we used PHP's print_r function instead of echo to display its contents. The pre tags above and below it separates each item out on to a new line, making it easier to read.

In the browser, we can see that it has printed a lot of information. We have port information, file locations, and many other fields. As mentioned earlier, the information on your system may vary.

Other Predefined Variables

Here are some often-used predefined variables and their usage:

  • $_POST: We used $_GET earlier in this chapter. $_POST is similar, but with one difference. $_GET fetches you the values from a query string, whereas $_POST contains the data from a form on any PHP page. You will use it more in later chapters.
  • $_FILES: If a file is uploaded from a form on a page, its information is available in the $_FILES array.
  • $_COOKIE: This allows basic text information to be stored as a cookie on the client's browser to be saved for later. A common example of this is if you log in to a website and tick Remember me, a cookie will be saved on the browser, which will be read on the next visit.
  • $_REQUEST: This contains the combined information of $_GET, $_POST, and $_COOKIE.
  • $_SESSION: These are session variables that are used to maintain state in the application. They allow values to be saved in memory for the duration of a session. This could be a username that is saved and displayed on the page while the session exists.
  • $GLOBALS: This contains all variables that are available to a script. It includes variables, data from $_GET, $_POST, any file upload data, session info, and cookie information.

Assignment by Value and by Reference

It is very important to be aware of different ways in which values can be assigned to a variable. In PHP, there are two ways to do it: assignment by value and assignment by reference. Let's look at each of these one by one.

Assignment by reference means assigning a reference of a variable using an ampersand with a variable like this: $var = &$othervar;. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Assignment by value means a value will be assigned to a new variable but has no reference back to any other variables. It's a standalone variable with a value.

Exercise 1.8: Assigning a Variable by Reference and Changing its Value

In this exercise, we will assign a variable by reference. Then, we will change the other variable's value and ensure that the original variable's value has also changed. Follow these steps:

  1. Move inside the chapter1 folder on your system.
  2. Create a new file named assignment.php in this folder.
  3. First, we will declare a $animal1 variable and assign the value Cat to it. Then, we declare another variable, $animal2, and assign the $animal1 variable to it. This means that the value of $animal1 is copied to the $animal2 variable. We then confirm this by echoing both variables in line 10, where we see that both variables have the value Cat:
    <?php 
    // Assignment by value
    echo 'Assignment by value';
    echo '<br>';
    $animal1 = 'Cat';
    $animal2 = $animal1;
    echo $animal1 . ' - ' . $animal2;
    echo '<br>';
  4. Next, when we write $animal2 = 'Dog', we change the value of the $animal2 variable to Dog and then again print both the variables. Now, we can see that although the value of $animal2 has changed, it did not have any effect on $animal1. This is what we call assignment by value. The value is just copied from one variable to the other, and both variables remain independent:
    $animal2 = 'Dog';
    echo $animal1 . ' - ' . $animal2;
    echo '<br>';

    Now, let's look at assignment by reference. "By reference" means that the new variable becomes an alias of the older variable. Hence, changing the value of the new variable changes the value of the older variable.

  5. Now, we will declare another variable, $animal3, with the value set to Elephant. Next, we create a new variable, $animal4, and assign the value of the $animal3 variable to it. While doing the assignment, note the ampersand (&) before the variable name. This ampersand tells PHP to assign the $animal4 variable to the $animal3 variable by reference. In the code, we will verify the value of both the variables by printing values of both variables, and they are the same:
    // Assignment by reference
    echo 'Assignment by reference';
    echo '<br>';
    $animal3 = 'Elephant';
    $animal4 = &$animal3;
    echo $animal3 . ' - ' . $animal4;
    echo '<br>';
    $animal4 = 'Giraffe';
  6. To see assignment by reference in action, we change the value of $animal4 to Giraffe. After this, we print both variables again and can see clearly that changing the value of $animal4 has changed the value of $animal3 as well:
    echo $animal3 . ' - ' . $animal4;
    ?>
  7. Now, open the browser and point to our file by opening this URL:
    http://localhost:8085/assignment.php

    You should see a screen like this:

Figure 1.14: Printing output to the browser

Figure 1.14: Printing output to the browser

Unless specified, variables are always assigned by value in PHP.

Using isset to Check for Variable Declaration

At times, we need to check whether a variable has been set, especially in cases where there is some user input from a form, and we need to verify it before saving it to the database. isset is a built-in PHP function that returns true for declared variables with values other than null.

Null data types are used when a variable has no value.

Let's do an exercise.

Exercise 1.9: Using isset to Check whether a Variable Has Been Set

In this exercise, we will use PHP's isset function to check whether a variable has been set. Follow these steps:

  1. Go to the chapter1 folder on your system.
  2. Create a new file named isset.php.
  3. Write the following code in isset.php and save the file:
    <?php 
    $name1 = '';
    $name2 = null;
    echo 'checking $name1 : ';
    var_dump(isset($name1));
    echo '<br>';
    echo 'checking $name2: ';
    var_dump(isset($name2));
    echo '<br>';
    echo 'checking undeclared variable $name3: ';
    var_dump(isset($name3));
    ?>
  4. Now, run the built-in PHP web server using the php -S localhost:8085 command. Make sure that you are in the chapter1 folder.
  5. Open the following URL in your browser:
     http://localhost:8085/isset.php 

    You should see a screen like this:

Figure 1.15: Printing the output

Figure 1.15: Printing the output

var_dump is a built-in PHP function that is used to print a variable's value and type. It's useful to see the contents of a variable and also what data type it contains. You can then make decisions about how to work with the variable based on this information.

isset is a built-in PHP function that determines whether a variable is declared and is different to NULL.

In the preceding code, we have declared two variables, $name1 and $name2. $name1 is an empty string and $name2 is set to null. $name3 is not declared. Then, we use PHP's var_dump function to print $name1, $name2, and $name3. Since PHP does not require declaring variables, we can use $name3.

On printing the values, we can see that the isset function returned true for $name1, which means a valid value is set for $name1. This is because $name1 has a valid value – an empty string. But it is returning false for $name2 because it is set to null, meaning that $name2 is not set.

Lastly, we dumped info about an undeclared variable, $name3. Since this is not declared at all, the isset function returned false, meaning this variable is also not set.

isset is a handy function, and you will be using it a lot when working with data.

A related function to isset is unset, which clears the value of a variable.

Activity 1.1: Displaying Query Strings in the Browser

In this activity, we will apply the knowledge gained from the earlier exercises and use variables to retrieve query strings from a URL and print the relevant information to the browser.

You will create a simple application that allows users to view movie information in the browser. Once you complete the activity, you should have an output similar to the following:

Figure 1.16: Expected outcome

Figure 1.16: Expected outcome

These steps will help you complete the activity:

  1. Create a file named movies.php.
  2. Capture query string data in the file to store the details of the movies, such as movie names, actor/actress names, and release year.
  3. Create a basic HTML structure and then display the captured query strings.
  4. Go to the Terminal and execute the command to start the built-in web server.
  5. After the web server is up and running, open the PHP page and append your query strings to the URL in your browser.

    Note

    The solution for this activity can be found via this link.

Summary

In this chapter, we learned what PHP is and where it stands in the market today. We also explored PHP's built-in templating engine and the interactive shell. The templating engine allows us to mix PHP and HTML in the same file. Then, using Terminal, we learned that we can run a PHP script using its built-in web server, which allows the output of a script to be viewed in a browser by going to the server's IP address (localhost in this case) and filename.

We learned how to create and assign variables – by value and by reference. We also saw how to use PHP's predefined variables and how they are used.

Finally, we learned how to run PHP's built-in web server and use query strings in our code. Appending data to the query string allowed us to pass extra data to the PHP script, where it could be displayed or modified by the script.

In the next chapter, we will take a look at different types used in PHP programming.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • 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

Description

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.

Who is this book for?

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.

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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 31, 2019
Length: 604 pages
Edition : 1st
Language : English
ISBN-13 : 9781838647285
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 31, 2019
Length: 604 pages
Edition : 1st
Language : English
ISBN-13 : 9781838647285
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 10,426.97
The Python Workshop
₹4691.99
The PHP Workshop
₹2457.99
The JavaScript Workshop
₹3276.99
Total 10,426.97 Stars icon
Banner background image

Table of Contents

10 Chapters
1. Introducing PHP Chevron down icon Chevron up icon
2. Types and Operators Chevron down icon Chevron up icon
3. Control Statements Chevron down icon Chevron up icon
4. Functions Chevron down icon Chevron up icon
5. Object-Oriented Programming Chevron down icon Chevron up icon
6. Using HTTP Chevron down icon Chevron up icon
7. Data Persistence Chevron down icon Chevron up icon
8. Error Handling Chevron down icon Chevron up icon
9. Composer Chevron down icon Chevron up icon
10. Web Services Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(4 Ratings)
5 star 50%
4 star 25%
3 star 0%
2 star 25%
1 star 0%
William Hall Dec 31, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The PHP Workshop, by Packt publications, is a great source for anyone interested in learning PHP; as well as a valuable resource for established developers. The workbook walks you through all of the basics of coding with PHP, including HTML and CSS; with plenty of code examples to try out and help you learn quicker. Even if you've never used PHP before, this workbook makes it easy to understand.Data types, variables, booleans, arrays, for loops, nested for loops, switch statements, functions, expressions, Object Oriented Programming basics, APIs, error handling, working with databases, reading/writing files, ...etc.; basically anything you need to know about programming in PHP. By the end of the workbook, you will be familiar enough with PHP to create you very own web application.I thought the book was very well written, with easy to follow examples of coding real world problems, and I would highly recommend it to anyone; whether a beginner in coding with PHP, or a more advanced user. The book also has all the answer code for the chapter activities in the appendix, but be sure to try each of them yourself first.I own several other Packt publications; all of them are high quality, very informative, and well researched and put together. The PHP Workshop book is no exception. Make sure to add this book to your PHP resource shelf (virtual or physical).
Amazon Verified review Amazon
Nicola Jun 21, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Ottimo Libro , compreso di corso on-line con certificato fine corso, consiglio vivamente, ben fatto!!
Amazon Verified review Amazon
L Feb 15, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Disclosure: I received this book in order to review it. What follows are my thoughts after reading the book itself.The PHP Workshop does a great job of introducing PHP from the ground up. You begin as you do most programming books, with the basics of the language. It then begins to delve into the more popular topics, like OOP, handling/sending HTTP requests, I/O interactions, Database interactions, Error Handling, and using Composer(package/dependency manager. The code examples are easy to spot and read, and don't distract from the surrounding text either.The main issues I have with the book are minor in scale: The pages seem to alternate between right centering and left centering which can be a little jarring. This is amplified by having certain code block sections run over into the next page(which is also something I was not thrilled about). Lastly, the choice to include images of the console and its output is not a bad one, but I felt it tended to distract me more than anything due to its stark contrast in color to the rest of the page.Other than that, if you have a foundation in programming, and want to pick up a good reference book on PHP, or you are starting your web development journey, this is a solid choice that can help you achieve your goals!
Amazon Verified review Amazon
Artgcen Jan 08, 2021
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Simple put. I don't recommend this book. It's confusing, to say the least. You can get a better understanding of PHP using online resources.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.