© David Powers 2019
David PowersPHP 7 Solutionshttps://doi.org/10.1007/978-1-4842-4338-1_3

3. How to Write PHP Scripts

David Powers1 
(1)
London, UK
 

This chapter offers a quick overview of how PHP works and gives you the basic rules. It’s aimed primarily at readers who have no previous experience of PHP or coding. Even if you’ve worked with PHP before, check the main headings to see what this chapter contains and brush up your knowledge on any aspects that you’re a bit hazy about.

This chapter covers
  • Understanding how PHP is structured

  • Embedding PHP in a web page

  • Storing data in variables and arrays

  • Getting PHP to make decisions

  • Looping through repetitive tasks

  • Using functions for preset tasks

  • Displaying PHP output

  • Understanding PHP error messages

PHP: The Big Picture

At first glance, PHP code can look quite intimidating, but once you understand the basics, you’ll discover that the structure is remarkably simple. If you have worked with any other computer language, such as JavaScript or jQuery, you’ll find they have a lot in common.

Every PHP page must have the following:
  • The correct filename extension, usually .php

  • PHP tags surrounding each block of PHP code (the closing PHP tag is optional if the file contains only PHP code)

A typical PHP page will use some or all of the following elements:
  • Variables to act as placeholders for unknown or changing values

  • Arrays to hold multiple values

  • Conditional statements to make decisions

  • Loops to perform repetitive tasks

  • Functions or objects to perform preset tasks

Let’s take a quick look at each of these in turn, starting with the filename and the opening and closing tags.

Telling the server to process PHP

PHP is a server-side language . The web server—usually Apache—processes your PHP code and sends only the results, usually as HTML, to the browser. Because all the action is on the server, you need to tell it that your pages contain PHP code. This involves two simple steps:
  • Give every page a PHP filename extension; the default is .php. Use a different extension only if you are specifically told to do so by your hosting company.

  • Identify all PHP code with PHP tags.

The opening tag is <?php and the closing tag is ?>. If you put the tags on the same line as surrounding code, there doesn’t need to be a space before the opening tag or after the closing one, but there must be a space after the php in the opening tag like this:
<p>This is HTML with embedded PHP<?php //some PHP code ?>.</p>
When inserting more than one line of PHP, it’s a good idea to put the opening and closing tags on separate lines for the sake of clarity.
<?php
// some PHP code
// more PHP code
?>

You may come across <? as an alternative short version of the opening tag. However, <? isn’t enabled on all servers. Stick with <?php, which is guaranteed to work.

When a file contains only PHP code, it’s strongly recommended to omit the closing PHP tag. This avoids potential problems when working with include files (see Chapter 5).

Note

To save space, most examples in this book omit the PHP tags. You must always use them when writing your own scripts or embedding PHP into a web page.

Embedding PHP in a Web Page

PHP is an embedded language . This means that you can insert blocks of PHP code inside ordinary web pages. When somebody visits your site and requests a PHP page, the server sends it to the PHP engine, which reads the page from top to bottom looking for PHP tags. HTML and JavaScript pass through untouched, but whenever the PHP engine encounters a <?php tag, it starts processing your code and continues until it reaches the closing ?> tag (or the end of the script if nothing follows the PHP code). If the PHP produces any output, it’s inserted at that point.

Tip

A page can have multiple PHP code blocks, but they cannot be nested inside each other.

Figure 3-1 shows a block of PHP code embedded in an ordinary web page and what it looks like in a browser and in a page-source view after it has been passed through the PHP engine. The code calculates the current year, checks whether it’s different from a fixed year (represented by $startYear in line 26 of the code on the left of the figure), and displays the appropriate year range in a copyright statement. As you can see from the page-source view at the bottom right of the figure, there’s no trace of PHP in what’s sent to the browser.
../images/332054_4_En_3_Chapter/332054_4_En_3_Fig1_HTML.jpg
Figure 3-1.

The PHP code remains on the server; only the output is sent to the browser

Tip

PHP doesn’t always produce direct output for the browser. It may, for instance, check the contents of form input before sending an email message or inserting information into a database. Therefore, some code blocks are placed above or below the main HTML code, or in external files. Code that produces direct output, however, goes where you want the output to be displayed.

Storing PHP in an External File

As well as embedding PHP in HTML, it’s common practice to store frequently used code in separate files. When a file contains only PHP code, the opening <?php tag is mandatory, but the closing ?> tag is optional. In fact, the recommended practice is to leave out the closing PHP tag. However, you must use the closing ?> tag if the external file contains HTML after the PHP code.

Using Variables to Represent Changing Values

The code in Figure 3-1 probably looks like a very long-winded way to display a range of years. But the PHP solution saves you time in the long run. Instead of your needing to update the copyright statement every year, the PHP code does it automatically. You write the code once and forget it. What’s more, as you’ll see in Chapter 5, if you store the code in an external file, any changes to the external file are reflected on every page of your site.

This ability to display the year automatically relies on two key aspects of PHP: variables and functions . As the name suggests, functions do things; they perform preset tasks, such as getting the current date and converting it into human-readable form. I’ll cover functions a little later, so let’s work on variables first. The script in Figure 3-1 contains two variables: $startYear and $thisYear.

Tip

A variable is simply a name that you give to something that may change or that you don’t know in advance. Variables in PHP always begin with $ (a dollar sign).

We use variables all the time in everyday life without thinking about it. When you meet somebody for the first time, you might ask “What’s your name?” It doesn’t matter whether the person is called Tom, Dick, or Harriet, the word “name” remains constant. Similarly, with your bank account, money goes in and out all the time (mostly out, it seems), but as Figure 3-2 shows, it doesn’t matter whether you’re scraping the bottom of the barrel or as rich as Croesus, the amount available is always called the balance.
../images/332054_4_En_3_Chapter/332054_4_En_3_Fig2_HTML.jpg
Figure 3-2.

The balance on your bank statement is an everyday example of a variable—the name stays the same, even though the value may change from day to day

So, “name” and “balance” are everyday variables. Just put a dollar sign in front of them and you have two ready-made PHP variables, like this:
$name
$balance

Simple.

Naming variables

You can name a variable just about anything you like, as long as you keep the following rules in mind:
  • Variables always begin with a dollar sign ($).

  • Valid characters are letters, numbers, and the underscore.

  • The first character after the dollar sign must be a letter or the underscore(_).

  • No spaces or punctuation marks are allowed, except for the underscore.

  • Variable names are case-sensitive: $startYear and $startyear are not the same.

When naming variables, choose something that tells you what it’s for. The variables you’ve seen so far—$startYear, $thisYear, $name, and $balance—are good examples. It’s a good idea to capitalize the first letter of the second or subsequent words when combining them (sometimes called camel case). Alternatively, you can use an underscore ($start_year, $this_year, etc.).

Tip

Accented characters commonly used in Western European languages are valid in variables. For example, $prénom and $förnamn are acceptable. In practice, you can also use other alphabets, such as Cyrillic, and nonalphabetic scripts, such as Japanese kanji, in variable names in PHP 7; but at the time of this writing, such use is undocumented, so I recommend sticking to the preceding rules.

Don’t try to save time by using really short variables. Using $sy, $ty, $n, and $b instead of the more descriptive ones makes code harder to understand—and that makes it hard to write. More important, it makes errors more difficult to spot. As always, there are exceptions to a rule. By convention, $i, $j, and $k are frequently used to keep count of the number of times a loop has run, and $e and $t are used in error checking. You’ll see examples of these later in this chapter.

Caution

Although you have considerable freedom in the choice of variable names, you can’t use $this, because it has a special meaning in PHP object-oriented programming. It’s also advisable to avoid using any of the keywords listed at https://secure.php.net/manual/en/reserved.php .

Assigning values to variables

Variables get their values from a variety of sources, including the following:
  • User input through online forms

  • A database

  • An external source, such as a news feed or XML file

  • The result of a calculation

  • Direct inclusion in the PHP code

Wherever the value comes from, it’s always assigned with an equal sign (=), like this:
$variable = value;

The variable goes on the left of the equal sign, and the value goes on the right. Because it assigns a value, the equal sign is called the assignment operator.

Caution

Familiarity with the equal sign from childhood makes it difficult to get out of the habit of thinking that it means “is equal to.” However, PHP uses two equal signs (==) to signify equality. This is a major cause of beginner mistakes, and it sometimes catches more experienced developers, too. The difference between = and == is covered in more detail later in this chapter.

Ending commands with a semicolon

PHP is written as a series of commands or statements. Each statement normally tells the PHP engine to perform an action, and it must always be followed by a semicolon, like this:
<?php
do this;
now do something else;
?>

As with all rules, there is an exception: you can omit the semicolon after the last statement in a code block. However, don’t do it except when using the short echo tag as described later in this chapter. Unlike JavaScript, PHP won’t assume there should be a semicolon at the end of a line if you leave it out. This has a nice side effect: you can spread long statements over several lines for ease of reading. PHP, like HTML, ignores whitespace in code. Instead, it relies on semicolons to indicate where one command ends and the next one begins.

Tip

A missing semicolon will bring your script to a grinding halt.

Commenting scripts

PHP treats everything as statements to be executed unless you mark a section of code as a comment. The following three reasons explain why you may want to do this:
  • To insert a reminder of what the script does

  • To insert a placeholder for code to be added later

  • To disable a section of code temporarily

When a script is fresh in your mind, it may seem unnecessary to insert anything that isn’t going to be processed. However, if you need to revise the script several months later, you’ll find comments much easier to read than trying to follow the code on its own. Comments are also vital when you’re working in a team. They help your colleagues understand what the code is intended to do.

During testing, it’s often useful to prevent a line of code, or even a whole section, from running. PHP ignores anything marked as a comment, so this is a useful way of turning on and off code.

There are three ways of adding comments: two for single-line comments and one for comments that stretch over several lines.

Single-line comments

The most common type of single-line comment begins with two forward slashes, like this:
// this is a comment and will be ignored by the PHP engine
PHP ignores everything from the double slashes to the end of the line, so you can also place comments alongside code (but only to the right):
$startYear = 2018; // this is a valid comment

Comments aren’t PHP statements, so they don’t end with a semicolon. But don’t forget the semicolon at the end of a PHP statement that’s on the same line as a comment.

An alternative style uses the hash or pound sign (#), like this:
# this is another type of comment that will be ignored by the PHP engine
$startYear = 2018; # this also works as a comment
This style of commenting often indicates sections of a longer script, like this:
##################
## Menu section ##
##################

Multiline comments

For a comment to stretch over several lines, use the same style as in Cascading Style Sheets (CSS) and JavaScript. Anything between /* and */ is treated as a comment, like this:
/* This is a comment that stretches
   over several lines. It uses the same
   beginning and end markers as in CSS. */

Multiline comments are particularly useful when testing or troubleshooting, as they can be used to disable long sections of script without the need to delete them.

Tip

Good comments and well-chosen variable names make code easier to understand and maintain.

Using arrays to Store Multiple Values

PHP lets you store multiple values in a special type of variable called an array . A simple way of thinking about arrays is that they’re like a shopping list. Although each item might be different, you can refer to them collectively by a single name. Figure 3-3 demonstrates this concept: the variable $shoppingList refers collectively to all five items—wine, fish, bread, grapes, and cheese.
../images/332054_4_En_3_Chapter/332054_4_En_3_Fig3_HTML.jpg
Figure 3-3.

Arrays are variables that store multiple items, just like a shopping list

Individual items—or array elements —are identified by means of a number in square brackets immediately following the variable name. PHP assigns the number automatically, but it’s important to note that the numbering always begins at 0. So the first item in the array, wine in our example, is referred to as $shoppingList[0], not $shoppingList[1]. And although there are five items, the last one (cheese) is $shoppingList[4]. The number is referred to as the array key or index, and this type of array is called an indexed array .

PHP uses another type of array in which the key is a word (or any combination of letters and numbers). For instance, an array containing details of this book might look like this:
$book['title'] = 'PHP 7 Solutions: Dynamic Web Design Made Easy, Fourth Edition';
$book['author'] = 'David Powers';
$book['publisher'] = 'Apress';

This type of array is called an associative array . Note that the array key is enclosed in quotes (single or double, it doesn’t matter).

Arrays are an important and useful part of PHP. You’ll use them a lot, starting with Chapter 5, when you’ll store details of images in an array to display a random image on a web page. Arrays are also used extensively with databases as you fetch the results of a search in a series of arrays.

Note

You can learn the various ways of creating arrays in Chapter 4.

PHP’s built-in Superglobal Arrays

PHP has several built-in arrays that are automatically populated with useful information. They are called superglobal arrays, and they normally begin with a dollar sign followed by an underscore. The only exception is $GLOBALS, which contains references to all variables in the global scope of the script (see “Variable scope—functions as black boxes” in Chapter 4 for a description of scope).

Two superglobals that you will see frequently are $_POST and $_GET. They contain information passed from forms through the Hypertext Transfer Protocol (HTTP) post and get methods, respectively. The superglobals are all associative arrays, and the keys of $_POST and $_GET are automatically derived from the names of form elements or variables in a query string at the end of a URL.

Let’s say you have a text input field called “address” in a form; PHP automatically creates an array element called $_POST['address'] when the form is submitted by the post method or $_GET['address'] if you use the get method. As Figure 3-4 shows, $_POST['address'] contains whatever value a visitor enters in the text field, enabling you to display it onscreen, insert it in a database, send it to your email inbox, or do whatever you want with it.
../images/332054_4_En_3_Chapter/332054_4_En_3_Fig4_HTML.jpg
Figure 3-4.

You can retrieve the values of user input through the $_POST array, which is created automatically when a form is submitted using the post method

You’ll work with the $_POST array in Chapter 6 when you send the content of an online feedback form by email to your inbox. Other superglobal arrays that you’ll use in this book are $_SERVER, to get information from the web server in Chapters 5, 14, and 15, $_FILES to upload files to your web site in Chapter 8, and $_SESSION, to create a simple login system in Chapters 11 and 19.

Caution

Don’t forget that variable names in PHP are case-sensitive. All superglobal array names are written in uppercase. $_Post or $_Get, for example, won’t work.

Understanding When to Use Quotes

If you look closely at the PHP code block in Figure 3-1, you’ll notice that the value assigned to the first variable isn’t enclosed in quotes. It looks like this:
$startYear = 2018;
Yet all the examples in “Using arrays to store multiple values” did use quotes, like this:
$book['title'] = 'PHP 7 Solutions: Dynamic Web Design Made Easy, Fourth Edition';
The simple rules are as follows:
  • Numbers: No quotes

  • Text: Requires quotes

As a general principle, it doesn’t matter whether you use single or double quotes around text or a string, as text is called in PHP and other computer languages. The situation is a bit more complex, as explained in Chapter 4, because there’s a subtle difference in the way single and double quotes are treated by the PHP engine.

Note

The word “string” is borrowed from computer and mathematical science, where it means a sequence of simple objects—in this case, the characters in text.

Quotes must always be in matching pairs, so you need to be careful about including apostrophes in a single-quoted string or double quotes in a double-quoted string. Examine the following line of code:
$book['description'] = 'This is David's latest book on PHP.';
At first glance, there seems to be nothing wrong with it. However, the PHP engine sees things differently than the human eye does, as Figure 3-5 demonstrates.
../images/332054_4_En_3_Chapter/332054_4_En_3_Fig5_HTML.jpg
Figure 3-5.

An apostrophe inside a single-quoted string confuses the PHP engine

There are two ways around this problem:
  • Use double quotes if the text includes any apostrophes.

  • Precede apostrophes with a backslash (this is known as escaping).

So, either of the following is acceptable:
$book['description'] = "This is David's latest book on PHP.";
$book['description'] = 'This is David's latest book on PHP.';
The same applies with double quotes in a double-quoted string (although with the rules reversed). The following code causes a problem:
$play = "Shakespeare's "Macbeth"";
In this case, the apostrophe is fine, because it doesn’t conflict with the double quotes, but the opening quotes in front of Macbeth bring the string to a premature end. To solve the problem, either of the following is acceptable:
$play = 'Shakespeare's "Macbeth"';
$play = "Shakespeare's "Macbeth"";
In the first example, the entire string has been enclosed in single quotes. This gets around the problem of the double quotes surrounding Macbeth but introduces the need to escape the apostrophe in Shakespeare’s. The apostrophe presents no problem in a double-quoted string, but the double quotes around Macbeth both need to be escaped. So, to summarize:
  • Single quotes and apostrophes are fine inside a double-quoted string.

  • Double quotes are fine inside a single-quoted string.

  • Anything else must be escaped with a backslash.

Tip

Use single quotes most of the time and reserve double quotes for situations where they have a special meaning, as described in Chapter 4.

Special Cases: True, False, and null

Although text should be enclosed in quotes, three keywords—true, false, and null—should never be unless you want to treat them as strings. The first two mean what you expect; null means “nonexistent value.”

Note

True and false are known as Boolean values . They’re named after nineteenth-century mathematician George Boole whose system of logical operations became the basis of much modern-day computing.

As the next section explains, PHP makes decisions based on whether something equates to true or false. Putting quotes around false has surprising consequences. Consider the following code:
$OK = 'false';

This does exactly the opposite of what you might expect: it makes $OK true! Why? Because the quotes around false turn it into a string, and PHP treats strings as true. (There’s a more detailed explanation in “The truth according to PHP” in Chapter 4.)

The keywords true, false, and null are case-insensitive. The following examples are all valid:
$OK = TRUE;
$OK = tRuE;
$OK = true;
So, to recap, PHP treats true, false, and null as special cases.
  • Don’t enclose them in quotes.

  • They are case-insensitive.

Making decisions

Decisions, decisions, decisions… Life is full of decisions. So is PHP. They enable it to change the output according to circumstances. Decision-making in PHP uses conditional statements. The most common of these uses if and closely follows the structure of normal language. In real life, you may be faced with the following decision (admittedly not very often in Britain): if the weather’s hot, I’ll go to the beach.

In PHP pseudocode, the same decision looks like this:
if (the weather's hot) {
    I'll go to the beach;
}
The condition being tested goes inside parentheses, and the resulting action goes between curly braces. This is the basic decision-making pattern:
if (condition is true) {
    // code to be executed if condition is true
}

Tip

Conditional statements are control structures and are not followed by a semicolon. The curly braces keep together one or more individual statements that are intended to be executed as a group.

The code inside the curly braces is executed only if the condition is true. If it’s false, PHP ignores everything between the braces and moves on to the next section of code. How PHP determines whether a condition is true or false is described in the following section.

Sometimes, the if statement is all you need, but you often want a default action to be invoked if the condition isn’t met. To do this, use else, like this:
if (condition is true) {
    // code to be executed if condition is true
} else {
    // default code to run if condition is false
}
If you want more alternatives, you can add more conditional statements like this:
if (condition is true) {
    // code to be executed if condition is true
} else {
    // default code to run if condition is false
}
if (second condition is true) {
    // code to be executed if second condition is true
} else {
    // default code to run if second condition is false
}
In this case both conditional statements will be run. If you want only one code block to be executed, use elseif like this:
if (condition is true) {
    // code to be executed if first condition is true
} elseif (second condition is true) {
    // code to be executed if first condition fails
    // but second condition is true
} else {
    // default code if both conditions are false
}

You can use as many elseif clauses in a conditional statement as you like. Only the first condition that equates to true will be executed; all others will be ignored, even if they’re also true. This means you need to build conditional statements in the order of priority that you want them to be evaluated. It’s strictly a first-come, first-served hierarchy.

Note

Although elseif is normally written as one word, you can use else if as separate words.

Making comparisons

Conditional statements are interested in only one thing: whether the condition being tested equates to true. If it’s not true, it must be false. There’s no room for half measures or maybes. Conditions often depend on the comparison of two values. Is this bigger than that? Are they both the same? And so on.

To test for equality, PHP uses two equal signs (==), like this:
if ($status == 'administrator') {
    // send to admin page
} else {
    // refuse entry to admin area
}

Caution

Don’t use a single equal sign in the first line ($status = 'administrator'). Doing so opens the admin area of your web site to everyone. Why? Because this automatically sets the value of $status to administrator; it doesn’t compare the two values. To compare values, you must use two equal signs. It’s a common mistake, but one with potentially disastrous consequences.

Size comparisons are performed using the mathematical symbols for less than (<) and greater than (>). Let’s say you’re checking the size of a file before allowing it to be uploaded to your server. You could set a maximum size of 50 KB like this (1 kilobyte = 1024 bytes):
if ($bytes > 51200) {
    // display error message and abandon upload
} else {
    // continue upload
}

Note

Chapter 4 describes how to test for multiple conditions simultaneously.

Using indenting and whitespace for clarity

Indenting code helps to keep statements in logical groups, making it easier to understand the flow of the script. PHP ignores any whitespace inside code, so you can adopt any style you like. Just be consistent so that you can spot anything that looks out of place.

Most people find indenting four or five spaces makes for the most readable code. Perhaps the biggest difference in styles lies in the position of curly braces. It’s common to put the opening brace on the same line as the preceding code, with the closing brace on a new line after the code block, like this:
if ($bytes > 51200) {
    // display error message and abandon upload
} else {
    // continue upload
}
However, others prefer this style:
if ($bytes > 51200)
{
    // display error message and abandon upload
}
else
{
    // continue upload
}

The style isn’t important. What matters is that your code is consistent and easy to read.

Using loops for Repetitive Tasks

Loops are huge timesavers because they perform the same task over and over again, yet involve very little code. They’re frequently used with arrays and database results. You can step through each item one at a time looking for matches or performing a specific task. Loops are particularly powerful in combination with conditional statements, allowing you to perform operations selectively on a large amount of data in a single sweep. Loops are best understood by working with them in a real situation. Details of all looping structures, together with examples, are in Chapter 4.

Using functions for Preset Tasks

Functions do things … lots of things, mind-bogglingly so in PHP. A typical PHP setup gives you access to several thousand built-in functions. You’ll only ever need to use a handful, but it’s reassuring to know that PHP is a full-featured language.

The functions you’ll be using in this book do truly useful things, such as get the height and width of an image, create thumbnails from existing images, query a database, send email, and much, much more. You can identify functions in PHP code because they’re always followed by a pair of parentheses. Sometimes, the parentheses are empty, as in the case of phpversion(), which you used in phpversion.php in the previous chapter. Often, though, the parentheses contain variables, numbers, or strings, like this line of code from the script in Figure 3-1:
$thisYear = date('Y');
This code calculates the current year and stores it in the variable $thisYear. It works by feeding the string 'Y' to the built-in PHP function date(). Placing a value between the parentheses like this is known as passing an argument to a function. The function takes the value in the argument and processes it to produce (or return) the result. For instance, if you pass the string 'M' as an argument to date() instead of 'Y', it will return the current month as a three-letter abbreviation (e.g., Mar, Apr, May). As the following example shows, you capture the result of a function by assigning it to a suitably named variable:
$thisMonth = date('M');

Note

Chapter 16 covers in depth how PHP handles dates and time.

Some functions take more than one argument. When this happens, separate the arguments with commas inside the parentheses, like this:
$mailSent = mail($to, $subject, $message);

It doesn’t take a genius to work out that this sends an email to the address stored in the first argument, with the subject line stored in the second argument, and the message stored in the third one. You’ll see how this function works in Chapter 6.

Tip

You’ll often come across the term “parameter” in place of “argument.” Technically speaking, parameter refers to a variable used in the function definition, while argument refers to an actual value passed to the function. In practice, both terms tend to be used interchangeably.

As if all the built-in functions weren’t enough, PHP lets you build your own custom functions, as described in the next chapter. Even if you don’t relish the idea of creating your own functions, throughout this book you’ll use some that I have made. You use them the same way as built-in functions.

Displaying PHP output

There’s not much point in all this wizardry going on behind the scenes unless you can display the results in your web page. There are two ways of doing this in PHP: using echo or print. There are some subtle differences between the two, but they are so subtle you can regard echo and print as identical. I prefer echo for the simple reason that it’s one fewer letter to type.

You can use echo with variables, numbers, and strings; simply put it in front of whatever you want to display, like this:
$name = 'David';
echo $name;   // displays David
echo 5;       // displays 5
echo 'David'; // displays David

When using echo or print with a variable, the variable must contain only a single value. You cannot use them to display the contents of an array or of a database result. This is where loops are so useful: you use echo or print inside the loop to display each element individually. You’ll see plenty of examples of this in action throughout the rest of the book.

You may see scripts that use parentheses with echo and print, like this:
echo('David'); // displays David

The parentheses make no difference. Unless you enjoy typing for the sake of it, leave them out.

Using the Short Echo Tag

When you want to display the value of a single variable or expression (and nothing else), you can use the short echo tag, which consists of an opening angle bracket, a question mark, and the equal sign, like this:
<p>My name is <?= $name ?>.</p>
This produces the same output as this:
<p>My name is <?php echo $name ?>.</p>

Because it’s shorthand for echo, no other code can be in the same PHP block, but it’s particularly useful when embedding database results in a web page. It goes without saying that the value of the variable must be set in a previous PHP block before you can use this shortcut.

Tip

Because no other code can be in the same PHP block, it’s common practice to omit the semicolon before the closing PHP tag when using the short echo tag.

Joining Strings Together

Although many other computer languages use the plus sign (+) to join text (strings), PHP uses a period, dot, or full stop (.), like this:
$firstName = 'David';
$lastName = 'Powers';
echo $firstName.$lastName; // displays DavidPowers

As the comment in the final line of code indicates, when two strings are joined like this, PHP leaves no gap between them. Don’t be fooled into thinking that adding a space after the period will do the trick. It won’t. You can put as much space on either side of the period as you like; the result will always be the same, because PHP ignores whitespace in code. In fact, it’s recommended to leave a space on either side of the period for readability.

To display a space in the final output, you must either include a space in one of the strings or insert the space as a separate string, like this:
echo $firstName . ' ' . $lastName; // displays David Powers

Tip

The period—or concatenation operator, to give it its correct name—can be difficult to spot among other code. Make sure the font size in your editor is large enough to see the difference between periods and commas.

Working with numbers

PHP can do a lot with numbers, from simple addition to complex math. The next chapter contains details of the arithmetic operators you can use with PHP. All you need to remember at this stage is that numbers must not contain any punctuation other than a decimal point. PHP will choke if you feed it numbers that contain commas (or anything else) as the thousands separator.

Understanding PHP error messages

Error messages are an unfortunate fact of life, so you need to understand what they’re trying to tell you. The following illustration shows a typical error message.

../images/332054_4_En_3_Chapter/332054_4_En_3_Figa_HTML.jpg

PHP error messages report the line where PHP discovered a problem. Most newcomers—quite naturally—assume that’s where to look for their mistake. Wrong…

Most of the time, PHP is telling you that something unexpected has happened. In other words, the mistake lies before that point. The preceding error message means that PHP discovered an echo command where there shouldn’t have been one. (Error messages always prefix PHP elements with T_, which stands for token.)

Instead of worrying what might be wrong with the echo command (probably nothing), start working backward, looking for anything missing, probably a semicolon or closing quote on a previous line.

Sometimes, the message reports the error on the last line of the script. That always means you have omitted a closing curly brace somewhere further up the page.

These are the main categories of errors, presented here in descending order of importance:
  • Fatal error: Any HTML output preceding the error will be displayed, but once the error is encountered—as the name suggests—everything else is killed stone dead. A fatal error is often caused by referring to a nonexistent file or function.

  • Parse error: This means there’s a mistake in your code syntax, such as mismatched quotes or a missing semicolon or closing brace. It stops the script in its tracks, and it doesn’t even allow any HTML output to be displayed.

  • Warning: A warning indicates a serious problem, such as a missing include file. (Include files are the subject of Chapter 5.) However, the error is usually not serious enough to prevent the rest of the script from being executed.

  • Deprecated: This warns you about features that are scheduled to be removed from a future version of PHP. If you see this type of error message, you should seriously consider updating your script, as it could suddenly stop working if your server is upgraded.

  • Strict: This type of error message warns you about using techniques that are not considered good practice.

  • Notice: This advises you about relatively minor issues, such as the use of a nondeclared variable. Although this type of error won’t stop your page from displaying (and you can turn off the display of notices), you should always try to eliminate them. Any error is a threat to your output.

Why is My Page Blank?

Many beginners are left scratching their heads when they load a PHP page into a browser and see absolutely nothing. There’s no error message, just a blank page. This happens when there’s a parse error—in other words, a mistake in the code—and the display_errors directive in php.ini is turned off.

If you followed the advice in the previous chapter, display_errors should be enabled in your local testing environment. However, most hosting companies turn off display_errors. This is good for security, but it can make it difficult to troubleshoot problems on your remote server. As well as parse errors, a missing include file often causes blank pages.

You can turn on the display of errors for an individual script by adding the following code right at the top of the page:
ini_set('display_errors', '1');

Put this code on the first line after the opening PHP tag, or in a separate PHP block at the top of the page if the PHP is lower down the page. When you upload the page and refresh the browser, you should see any error messages generated by PHP.

If you still see a blank page after adding this line of code, it means there’s an error in your syntax. Test the page locally with display_errors turned on to find out what’s causing the problem.

Caution

After correcting the error, remove the code that turns on the display of errors. If something else breaks in the script at a later stage, you don’t want to expose potential vulnerabilities on your live web site.

PHP Quick Checklist

This chapter contains a lot of information, but hopefully it has given you a broad overview of how PHP works. Here’s a reminder of some of the main points:
  • Always give PHP pages the correct filename extension, normally .php.

  • Enclose PHP code between the correct tags: <?php and ?>.

  • Avoid the short form of the opening tag: <?. Using <?php is more reliable.

  • Omit the closing PHP tag in files that contain only PHP code.

  • PHP variables begin with $ followed by a letter or the underscore character.

  • Choose meaningful variable names and remember they’re case-sensitive.

  • Use comments to remind you what your script does.

  • Numbers don’t require quotes, but strings (text) do.

  • The decimal point is the only punctuation allowed in numbers.

  • You can use either single or double quotes around strings, but the outer pair must match.

  • Use a backslash to escape quotes of the same type inside a string.

  • To store related items together, use an array.

  • Use conditional statements, such as if and if . . . else, for decision-making.

  • Loops simplify repetitive tasks.

  • Functions perform preset tasks.

  • Display PHP output with echo or print.

  • With most error messages, work backward from the position indicated.

  • Keep smiling—and remember that PHP is not difficult.

The next chapter fills in essential details that you can refer to as you progress through this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.127.232