Learn PHP in One Day and Learn It Well

PHP for Beginners with Hands-on Project. The only book you need to start coding in PHP immediately. By Jamie Chan

Chapter 3: Basic PHP Tasks

In the previous chapter, we installed XAMPP and Brackets and coded our first PHP script.

In this chapter, we’re going to learn to perform three very fundamental tasks in PHP – displaying outputs to users, duplicating code across multiple pages and redirecting users.

3.1 Displaying Outputs

Before we learn to display outputs, let’s create a PHP file to serve as a template for us to test the PHP statements in this section.

Create a file in Brackets and save it as output.php to your htdocs folder. Add the following code to output.php:

	//Add code here

Whenever you want to test any PHP statement in this section, you can add the statement to output.php (after the <?php opening tag) and load it in your browser to check the output.

Notice that we did not add a closing tag ( ?> ) to output.php? This is because output.php only contains PHP code.

According to the standard recommended by the PHP Framework Interop Group, any PHP script that only contains PHP code should not end with a closing tag. This is to prevent unwanted whitespaces at the end of the file, which can cause issues such as an “Headers already sent” warning when modifying response headers.

Do not worry if the statement above does not make any sense; we’ll learn about the “Headers already sent” warning later. For now, let’s move on to learn how to display outputs in PHP.

3.1.1 echo

The easiest way to display outputs in PHP is to use an echo statement. To do that, we enclose the text that we want to display in a pair of matching quotation marks after the echo keyword. The echo keyword is not case sensitive. Hence, echoEcho or ECHO will all work.

Using an echo statement is straightforward. We did that in Chapter 2 when we used it to display the words “Hello World!”.

In addition to using echo statements to display simple text messages, we can use them to display text with HTML markup. For instance, we can write

echo 'PHP is fun
and easy!';

This gives us

PHP is funand easy!

as the output; the text “and easy!” is displayed on the second line due to the <BR> tag.

We can also combine multiple messages in a single echo statement. To do that, we separate the messages with commas. For instance,

echo "ABCD", "EFGH";

gives us


as the output. Combining messages is useful when our message is more complex, such as when the message includes variables and functions. We’ll learn about variables and functions in later parts of the book.

Last but not least, we can use an echo statement with or without parentheses. You may have seen some code that does the following:

echo ("ABCD");

This is fine in most cases. However, if you use parentheses, you are not allowed to combine multiple messages in a single echo statement. For instance,

echo ("ABCD", "EFGH");

will give us an error. In most cases, you are better off using echo statements without parentheses.

3.1.2 print

Besides using echo statements to display outputs, we can use print statements.

 print statements are VERY similar to echo statements. Let’s look at an example:

print "My name is Brody.";

gives us

My name is Brody.

as the output. As you can see, the print statement works just like an echo statement. While there are some differences between them, in most cases, there is no need to use the print statement.

In PHP, it is fairly common that there is more than one way to perform a certain task. This is one of the main complaints developers have about PHP, as it complicates things unnecessarily. In most cases, the different ways are very similar to each other. In order not to overwhelm you with too many options, I’ll stick with one option in this book and briefly mention other options if necessary. In this book, I’ll be using echo statements to display outputs.

3.1.3 Escaping Characters

Next, let’s learn to escape characters in PHP.

In the previous sections, we learned to enclose text in quotation marks when we use an echo (or print ) statement. What happens if we want to display an apostrophe?

For instance, suppose we have the following statement:

echo '<BR>Today is Friday, we're going to the zoo.';

We’ll get an error when we try to run the statement above as PHP does not differentiate between an apostrophe and a quotation mark by default. Hence, it treats the apostrophe in the word “we’re” as a closing quotation mark. In other words, it sees the statement as

echo '<BR>Today is Friday, we'

and expects a semicolon or comma after the apostrophe. When that does not happen, PHP gets confused and gives us an error.

There are two ways to deal with the error above. The first is to use double quotation marks to enclose the text and rewrite the statement as

echo "<BR>Today is Friday, we're going to the zoo.";

As PHP uses a double quotation mark to close another double quotation mark, the apostrophe in “we’re” is not mistakenly interpreted as a closing quotation mark.

Alternatively, we can escape the apostrophe in the original statement by preceding it with a backslash character ( \ ).

Escaping a character alters the meaning of the character. Without the backslash character, the apostrophe is interpreted as a closing single quote. With it, it is treated as an apostrophe meant to be displayed on the browser.

For instance, to display the apostrophe in the previous example, we can use the statement below:

echo '<BR>Today is Friday, we\'re going to the zoo.';

This gives us the following output:

Today is Friday, we're going to the zoo.

Other common uses of the backslash character include:

Using it to display a double quotation mark

echo """;

gives us an error, while

echo "\"";

gives us


Using it to display the backslash character itself

echo "\";

gives us an error, while

echo "\\";

gives us


3.2 Duplicating Code

Next, let’s move on to learn how to duplicate code in our PHP scripts.

In PHP, generally speaking, scripts are independent of one another. Hence, code written in one PHP script (say, index.php) is not available once users navigate to another page.

If we want multiple pages on our website to have the same HTML or PHP code, we need to use the include statement.

3.2.1 include

Suppose you want multiple pages on your website to have the same <h1> heading, you do not need to copy and paste the code into all the pages manually. Instead, you can use the include statement.

Let’s try that out. Create a file called heading.html (in htdocs) and add the following code to it:

<h1>Welcome to PHP</h1>

Next, create another file called includedemo.php and save it to htdocs too. Add the following code to includedemo.php:

<!DOCTYPE html>
		include 'heading.html';

Notice the statement include 'heading.html'; in includedemo.php?

When PHP sees this statement, it goes to heading.html, “copies” the code inside, and “pastes” it into includedemo.php for us automatically. This saves us the trouble of having to copy and paste the code ourselves.

If you launch includedemo.php now, you’ll see the words “Welcome to PHP” displayed as a <h1> heading. This is due to the code in heading.html. Got it?

To use an include statement, we need to give PHP the path of the file we want it to include. This is similar to what we do in HTML when we link CSS or other external files to our webpages. In our example above, as heading.html is stored in the same folder as includedemo.php, we simply give it the filename.

If heading.html is stored in another folder (say in a folder called “includes” inside htdocs), we need to use the statement below:

include 'includes/heading.html';

3.2.2 require

Besides the include statement, PHP also has the require statement. The difference between the two is that require produces a fatal error and stops the script if PHP fails to find the file required.

 include , on the other hand, will only produce a warning without stopping the script.

If the content you want PHP to “copy and paste” into your file is crucial to the correct execution of the page, you should use the require statement. Otherwise, you can use the include statement.

3.2.3 include_once, require_once

Both the include and require statements come with a _once version.

As the names suggest, the include_once and require_once statements only “copy and paste” the code into the file once. These statements are useful in cases where the same file may be included more than once accidentally (for instance, when the script is so long you have lost track of whether you have included the file previously).

If you add another

include 'heading.html';

statement to includedemo.php (before the ?> tag) and load the page, you’ll get “Welcome to PHP” displayed as a <h1> heading twice.

On the other hand, if you change the include statements to

include_once 'heading.html';
include_once 'heading.html';

you’ll only get the <h1> heading displayed once.

3.3 Redirecting Users

Great! We’ve come to the last section of this chapter. In this section, we’ll learn to redirect users using PHP.

In HTML, we know that we can use a <meta> tag to redirect users to another page. In PHP, we use a built-in function called header() .

First off, what is a function?

A function is a block of code that performs a certain task. For an analogy, think of the functions in MS Excel. If we want to add the values of some cells in a spreadsheet, we can use a built-in function called sum(). This function is pre-written by other programmers and comes included with Excel.

Similar to the pre-written functions in Excel, PHP comes with many built-in functions. Most functions require us to provide certain information for them to perform their tasks. In PHP, we provide this information by enclosing them inside a pair of parentheses (in a pre-defined order) after the function name. The information that we pass to the function is known as arguments.

To use the header() function, we need to pass the word “Location”, followed by a colon and the redirect URL to the function. Using a function is also known as calling the function.

To call the header() function, add the following code to the start of includedemo.php (before the <!DOCTYPE html> tag):

	header('Location: http://example.com');

If you load includedemo.php now, you’ll be redirected tohttp://example.com. Got it?

When you use the header() function, note that it must be called before your script generates any output to the browser, either by normal HTML tags, blank lines, or from PHP. If there’s any output before the function is called, the function will not work. For instance, it will not work in the following two examples:

Example 1

   echo 'Hello';
   header('Location: http://example.com');

Example 2

<p>This is some text.</p>
   header('Location: http://example.com');

In the first example, output is generated by the echo statement ( echo 'Hello'; ) before the header() function is called.

In the second example, output is generated by the two lines of code before the <?php tag. These two lines generate an HTML paragraph and an empty line before the header() function is called.

If your script generates any output before the header() function is called, you’ll get the “Headers already sent” warning mentioned previously in Chapter 3.1 and users will not be redirected. The code may work when you are working on your local computer. However, when you upload it to your hosting company’s server, it will fail to work. Got it?