1. Introduction to PHP

Although this book focuses on using MySQL and PHP together, you’ll do the majority of your legwork using PHP alone. In this and the following chapter, you’ll learn PHP’s basics, from syntax to variables, operators, and language constructs (conditionals, loops, and whatnot). As you are picking up these fundamentals, you’ll also develop usable code that you’ll integrate into larger applications later in the book.

This introductory chapter will cruise through most of the basics of the PHP language. You’ll learn the syntax for coding PHP, how to send data to the browser, and how to use two kinds of variables—strings and numbers—plus constants. Some examples may seem inconsequential, but they’ll demonstrate ideas you’ll need to master in order to write more advanced scripts further down the line. The chapter concludes with some quick debugging tips…you know…just in case!

Basic Syntax

As stated in the book’s introduction, PHP is an HTML-embedded scripting language, meaning that you can intermingle PHP and HTML code within the same file. So to begin programming with PHP, start with a simple web page. Script 1.1 is an example of a no-frills, no-content HTML5 document, which will be used as the foundation for most web pages in the book (this book does not formally discuss HTML5; see a resource dedicated to the topic for more information). Please also note that the template uses UTF-8 encoding, a topic discussed in the following sidebar.

Script 1.1 A basic HTML5 page.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Page Title</title>
6   </head>
7   <body>
8      <!-- Script 1.1 - template.html -->
9   </body>
10   </html>

To add PHP code to a page, place it within PHP tags:

<?php
?>

Script 1.2 This first PHP script doesn't do anything, but it does demonstrate how a PHP script is written. It'll also be used as a test script, prior to getting into elaborate PHP code.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Basic PHP Page</title>
6   </head>
7   <body>
8      <!-- Script 1.2 - first.php -->
9      <p>This is standard HTML.</p>
10  <?php
11  ?>
12  </body>
13  </html>

Anything written within these tags will be treated by the web server as PHP, meaning the PHP interpreter will process the code. Any text outside of the PHP tags is immediately sent to the browser as regular HTML. Because PHP is most often used to create content displayed in the browser, the PHP tags are normally put somewhere within the page’s body.

Along with placing PHP code within PHP tags, your PHP files must have a proper extension. The extension tells the server to treat the script in a special way—namely, as a PHP page. Most web servers use .html for standard HTML pages and .php for PHP files.

Before getting into the steps, understand that you must already have a working PHP installation! This could be on a hosted site or your own computer, after following the instructions in Appendix A, “Installation.”

To make a basic PHP script:

1. Create a new document in your text editor or IDE, to be named first.php (Script 1.2).

It generally does not matter what application you use, be it Adobe Dreamweaver (a fancy IDE), Sublime Text (a great and popular plain-text editor), or vi (a plain-text Unix editor, lacking a graphical interface). Still, some text editors and IDEs make typing and debugging HTML and PHP easier (conversely, Notepad on Windows does some things that make coding harder: don’t use Notepad!). If you don’t already have an application you’re attached to, search online or use the book’s corresponding forum (LarryUllman.com/forums/) to find one.

2. Create a basic HTML document:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Basic PHP Page</title>
</head>
<body>
  <!-- Script 1.2 - first.php -->
  <p>This is standard HTML.</p>
</body>
</html>

This is a basic HTML5 page. One of the niceties of HTML5 is its minimal doctype and syntax.

3. Before the closing body tag, insert the PHP tags:

<?php
?>

These are the formal PHP tags, also known as XML-style tags. Although PHP supports other tag types, I recommend that you use the formal type, and I will do so throughout this book.

4. Save the file as first.php.

Remember that if you don’t save the file using an appropriate PHP extension, the script will not execute properly. (Just one of the reasons not to use Notepad is that it will secretly add the .txt extension to PHP files, thereby causing many headaches.)

5. Place the file in the proper directory of your web server.

If you are running PHP on your own computer (presumably after following the installation directions in Appendix A), you just need to move, copy, or save the file to a specific folder on your computer. Check Appendix A or the documentation for your particular web server to identify the correct directory, if you don’t already know what it is.

If you are running PHP on a hosted server (i.e., on a remote computer), you’ll need to use a Secure File Transfer Protocol (SFTP) application to upload the file to the proper directory. Your hosting company will provide you with access and the other necessary information.

6. Run first.php in your browser Letter A in a circle..

Screenshot of using echo page is shown. The page URL reads localhost/second.php. The output screen reads, “This is standard HTML. This was generated using PHP!”

Letter A in a circle.While it seems like any other (simple) HTML page, this is in fact a PHP script and the basis for the rest of the examples in the book.

Because PHP scripts need to be parsed by the server, you absolutely must access them via a URL (i.e., the address in the browser must begin with http:// or https://). You cannot simply open them in your browser as you would a file in other applications (in which case the address would start with file:// or C: or the like).

If you are running PHP on your own computer, you’ll need to use a URL like http://localhost/first.php, http://127.0.0.1/first.php, or http://localhost/~<user>/first.php (on macOS, using your actual username for <user>). If you are using a hosted site, you’ll need to use http://your-domain-name/first.php (e. g., http://www.example.com/first.php).

7. If you don’t see results like those in Letter A in a circle., start debugging!

Part of learning any programming language is mastering debugging. It’s a sometimes painful but absolutely necessary process. With this first example, if you don’t see a simple, but perfectly valid, web page, follow these steps:

A. Confirm that you have a working PHP installation (see Appendix A for testing instructions).

B. Make sure that you are running the script through a URL. The address in the browser must begin with http. If it starts with file://, that’s a problem Letter B in a circle..

Screenshot of a PHP code in a webpage titled first.php. The URL address bar reads, file:///users/larry/Sites/phpmysql5/first.php.

Letter B in a circle.PHP code will only be executed when run through http://.

C. If you get a file not found (or similar) error, you’ve likely put the file in the wrong directory or mistyped the file’s name (either when saving it or in your browser).

If you’ve gone through all this and you are still having problems, turn to the book’s corresponding forum (LarryUllman.com/forums/).


Tip

To find more information about HTML, check out Elizabeth Castro’s excellent HTML and CSS: Visual QuickStart Guide (Peachpit, 2013), or search online.



Tip

You can embed multiple sections of PHP code within a single HTML document (i.e., you can go in and out of the two languages). You’ll see examples of this throughout the book.



Tip

You can declare the encoding of an external CSS file by adding @charset “utf-8”; as the first line in the file. If you’re not using UTF-8, change the line accordingly.


Sending Data to the Browser

To create dynamic web sites with PHP, you must know how to send data to the browser. PHP has a number of built-in functions for this purpose; the most common are echo and print. I tend to favor echo:

echo 'Hello, world!';
echo "What's new?";

You could use print instead if you prefer (the name more obviously indicates what it does):

print 'Hello, world!';
print "What's new?";

As you can see from these examples, you can use either single or double quotation marks (but there is a distinction between the two types of quotation marks, which I’ll make clear by this chapter’s end). The first quotation mark after the function name indicates the start of the message to be printed. The next matching quotation mark (i.e., the next quotation mark of the same kind as the opening mark) indicates the end of the message to be printed.

Along with learning how to send data to the browser, you should also notice that in PHP all statements—a line of executed code, in layman’s terms—must end with a semicolon. Also, PHP is case-insensitive when it comes to function names, so , , , and so forth will all work. The all-lowercase version is easiest to type, of course.

Script 1.3 Using print or echo, PHP can send data to the browser.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Using Echo</title>
6   </head>
7   <body>
8      <!-- Script 1.3 - second.php -->
9      <p>This is standard HTML.</p>
10  <?php
11  echo 'This was generated using PHP!';
12  ?>
13  </body>
14  </html>

To send data to the browser:

1. Open first.php (refer to Script 1.2) in your text editor or IDE.

2. Between the PHP tags (lines 10 and 11), add a simple message (Script 1.3):

echo 'This was generated using Images PHP!';

It truly doesn’t matter what message you type here, which function you use (echo or print), or which quotation marks, for that matter—just be careful if you are printing a single or double quotation mark as part of your message (see the sidebar “Needing an Escape”).

3. If you want, change the page title to better describe this script (line 5):

<title>Using Echo</title>

This change affects only the browser window’s title bar.

4. Save the file as second.php, place it in your web directory, and test it in your browser Letter A in a circle..

Screenshot of using echo page is shown. The page URL reads localhost/second.php. The output screen reads, “This is standard HTML. This was generated using PHP!”

Letter A in a circle.The results still aren’t glamorous, but this page was in part dynamically generated by PHP.

Remember that all PHP scripts must be run through a URL (http://something)!

5. If necessary, debug the script.

If you see a parse error instead of your message Letter B in a circle., check that you have both opened and closed your quotation marks and escaped any problematic characters (see the sidebar). Also be certain to conclude each statement with a semicolon.

Screenshot of localhost page is shown. The file name reads localhost/second.php. The output screen shows a parse error.

Letter B in a circle.This may be the first of many parse errors you see as a PHP programmer (this one is caused by the omission of the terminating quotation mark).

If you see an entirely blank page, this is probably for one of two reasons:

▸ There is a problem with your HTML. Test this by viewing the source of your page and looking for HTML problems there Letter C in a circle..

Screenshot of a PHP page is shown where debugger tab is selected. The closing title tag of html is shown and highlighted.

Letter C in a circle.One possible cause of a blank PHP page is a simple HTML error, like the closing title tag here (it’s missing the slash).

▸ An error occurred, but display_errors is turned off in your PHP configuration, so nothing is shown. In this case, see the section in Appendix A on how to configure PHP so that you can turn display_errors back on.


Tip

Technically, echo and print are language constructs, not functions. That being said, don’t be bothered as I continue to call them “functions” for convenience. Also, as you’ll see later in the book, I include the parentheses when referring to functions—say, number_format(), not just number_format—to help distinguish them from variables and other parts of PHP. This is just my own little convention.



Tip

You can, and often will, use echo and print to send HTML code to the browser, like so Letter D in a circle.:

Screenshot of using echo output screen reads “Hello, world!” The word “world” is shown in boldface.

Letter D in a circle.PHP can send HTML code (like the formatting here) as well as simple text Letter A in a circle. to the browser.

echo '<p>Hello,
Images <strong>world</strong>!</p>';


Tip

echo and print can both be used over multiple lines:

echo 'This sentence is
printed over two lines.';

What happens in this case is that the return (created by pressing Enter or Return) becomes part of the printed message and isn’t terminated until the closing quotation mark. The net result will be the “printing” of the return in the HTML source code Letter E in a circle.. This will not have an effect on the generated page Letter F in a circle.. For more on this, see the sidebar “Understanding White Space.”

Screenshot of a PHP page is shown where debugger tab is selected.

Letter E in a circle. Printing text and HTML over multiple PHP lines will generate HTML source code that also extends over multiple lines. Note that extraneous white spacing in the HTML source will not affect the look of a page Letter F in a circle. but can make the source easier to review.

Screenshot of using echo screen reads the output “This sentence is printed over two lines” in a single line.

Letter F in a circle. The return in the HTML source Letter E in a circle. has no effect on the rendered result. The only way to alter the spacing of a displayed web page is to use HTML tags (like <br> and <p></p>).


Writing Comments

Creating executable PHP code is only a part of the programming process (admittedly, it’s the most important part). A secondary but still crucial aspect to any programming endeavor is documenting your code.

In HTML you can add comments using special tags:

<!-- Comment goes here. -->

HTML comments are viewable in the source but do not appear in the rendered page (see Letter E in a circle. and Letter F in a circle. in the previous section).

PHP comments are different in that they aren’t sent to the browser at all, meaning they won’t be viewable to the end user, even when looking at the HTML source.

PHP supports three comment syntaxes. The first uses what’s called the pound, hash, or number symbol (#):

# This is a comment.

The second uses two slashes:

// This is also a comment.

Both of these cause PHP to ignore everything that follows until the end of the line (when you press Return or Enter). Thus, these two comments are for single lines only. They are also often used to place a comment on the same line as some PHP code:

print 'Hello!'; // Say hello.

A third style allows comments to run over multiple lines:

/* This is a longer comment
that spans two lines. */

To comment your scripts:

1. Begin a new PHP document in your text editor or IDE, to be named comments.php, starting with the initial HTML (Script 1.4):

Script 1.4 These basic comments demonstrate the three comment syntaxes you can use in PHP.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Comments</title>
6   </head>
7   <body>
8   <?php
9
10  # Script 1.4 - comments.php
11  # Created March 16, 2011
12  # Created by Larry E. Ullman
13  # This script does nothing much.
14
15  echo '<p>This is a line of text.<br>This is another line of text.</p>';
16
17  /*
18  echo 'This line will not be executed.';
19  */
20
21  echo "<p>Now I'm done.</p>"; // End of PHP code.
22
23  ?>
24  </body>
25  </html>

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Comments</title>
</head>
<body>

2. Add the initial PHP tag and write your first comments:

<?php
# Script 1.4 - comments.php
# Created April 23, 2017
# Created by Larry E. Ullman
# This script does nothing much.

One of the first comments each script should contain is an introductory block that lists creation date, modification date, creator, creator’s contact informa-tion, purpose of the script, and so on. Some people suggest that the shell-style comments (#) stand out more in a script and are therefore best for this kind of notation.

3. Send some HTML to the browser:

echo '<p>This is a line of text.
Images <br>This is another line of
Images text.</p>';

It doesn’t matter what you do here—just make something for the browser to display. For the sake of variety, the echo statement will print some HTML tags, including a line break (<br>) to add some spacing to the generated HTML page.

4. Use the multiline comments to comment out a second echo statement:

/*
echo 'This line will not be
Images executed.';
*/

By surrounding any block of PHP code with /* and */, you can render that code inert without having to delete it from your script. By later removing the comment tags, you can reactivate that section of PHP code.

5. Add a final comment after a third echo statement:

echo "<p>Now I'm done.</p>";
Images // End of PHP code.

This last (superfluous) comment shows how to place a comment at the end of a line, a common practice. Note that double quotation marks surround this message, since single quotation marks would conflict with the apostrophe (see the “Needing an Escape” sidebar, earlier in the chapter).

6. Close the PHP section and complete the HTML page:

?>
</body>
</html>

7. Save the file as comments.php, place it in your web directory, and test it in your browser Letter A in a circle..

Screenshot of PHP comments screen reads “this is a line of text. This is another line of text. Now I’m done.” in three different lines.

Letter A in a circle. The PHP comments in Script 1.4 don’t appear in the web page or the HTML source Letter B in a circle..

8. If you’re the curious type, check the source code in your browser to confirm that the PHP comments do not appear there Letter B in a circle..

Screenshot of a PHP page is shown.

Letter B in a circle. The PHP comments from Script 1.4 are nowhere to be seen in the client’s browser.


Tip

You shouldn’t nest—place one inside another—multiline comments (/* */). Doing so will cause problems.



Tip

Any of the PHP comments can be used at the end of a line (say, after a function call):

echo 'Howdy'; /* Say 'Howdy' */

Although this is allowed, it’s far less common.



Tip

In the interest of saving space, the scripts in this book will not be as well documented as I would suggest they should be.



Tip

It’s also important that you keep the comments up to date and accurate when you change a script. There’s nothing more confusing than a comment that says one thing when the code really does something else.



Tip

Some developers argue that it’s unnecessary to comment individual bits of code because the code itself should make its purpose clear. In my experience, adding comments helps.


What Are Variables?

Variables are containers used to temporarily store values. These values can be numbers, text, or much more complex data. PHP supports eight types of variables. These include four scalar (single-valued) types—Boolean (TRUE or FALSE), integer, floating point (decimals), and strings (one or more characters); two nonscalar (multivalued)—arrays and objects; plus resources (which you’ll see when interacting with databases) and NULL (which is a special type that has no value).

Regardless of what type you are creating, all variable names in PHP follow certain syntactical rules:

Images A variable’s name must start with a dollar sign ($)—for example, $name.

Images The variable’s name can contain a combination of letters, numbers, and the underscore—for example, $my_report1.

Images The first character after the dollar sign must be either a letter or an underscore (it cannot be a number).

Images Variable names in PHP are case-sensitive! This is a very important rule. It means that $name and $Name are different variables.

To begin working with variables, this next script will print out the value of three predefined variables. Whereas a standard variable is assigned a value during the execution of a script, a predefined variable will already have a value when the script begins its execution. Most of these predefined variables reflect properties of the server as a whole, such as the operating system in use.

Before getting into this script, there are two more things you should know. First, variables can be assigned values using the equals sign (=), also called the assignment operator. Second, to display the value of a variable, you can print the variable without quotation marks:

print $some_var;

Or variables can be printed within double quotation marks:

print "Hello, $name";

You cannot print variables within single quotation marks:

print 'Hello, $name';
Images // This won't work!

To use variables:

1. Begin a new PHP document in your text editor or IDE, to be named predefined.php, starting with the initial HTML (Script 1.5):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Predefined Variables</title>
</head>
<body>

2. Add the opening PHP tag and the first comment:

<?php # Script 1.5 - predefined.php

Script 1.5 This script prints three of PHP's many predefined variables.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Predefined Variables</title>
6   </head>
7   <body>
8   <?php # Script 1.5 - predefined.php
9
10  // Create a shorthand version of the variable names:
11  $file = $_SERVER['SCRIPT_FILENAME'];
12  $user = $_SERVER['HTTP_USER_AGENT'];
13  $server = $_SERVER['SERVER_SOFTWARE'];
14  
15  // Print the name of this script:
16  echo "<p>You are running the file:<br><strong>$file</strong>.</p>
";
17
18  // Print the user's information:
19  echo "<p>You are viewing this page using:<br><strong>$user</strong></p>
";
20
21  // Print the server's information:
22  echo "<p>This server is running:<br><strong>$server</strong>.</p>
";
23
24  ?>
25  </body>
26  </html>

From here on out, scripts will no longer comment on the creator, creation date, and so forth, although you should continue to document your scripts thoroughly. Scripts will, however, make a comment indicating the script’s number and filename for ease of cross-referencing (both in the book and when you download them from the book’s supporting web site, LarryUllman.com).

3. Create a shorthand version of the first variable to be used in this script:

$file = $_SERVER['SCRIPT_FILENAME'];

This script will use three variables, each of which comes from the larger predefined $_SERVER variable. $_SERVER refers to a mass of server-related information. The first variable the script uses is $_SERVER[‘SCRIPT_FILENAME’]. This variable stores the full path and name of the script being run (for example, C:Program FilesApachehtdocs predefined.php).

The value stored in $_SERVER[‘SCRIPT _FILENAME’] will be assigned to the new variable $file. Creating new variables with shorter names and then assigning them values from $_SERVER will make it easier to refer to the variables when printing them. (It also gets around another issue you’ll learn about in due time.)

4. Create a shorthand version of two more variables:

$user = $_SERVER
Images ['HTTP_USER_AGENT'];
$server = $_SERVER
Images ['SERVER_SOFTWARE'];

$_SERVER[‘HTTP_USER_AGENT’] represents the browser and operating system of the user accessing the script. This value is assigned to $user.

$_SERVER[‘SERVER_SOFTWARE’] represents the web application on the server that’s running PHP (e.g., Apache, Abyss, Xitami, or IIS). This is the program that must be installed (see Appendix A) in order to run PHP scripts on that computer.

5. Print out the name of the script being run:

echo "<p>You are running the
Images file:<br /><strong>$file
Images </strong>.</p>
";

The first variable to be printed is $file. Notice that this variable must be used within double quotation marks and that the statement also makes use of the PHP newline character ( ), which will add a line break in the generated HTML source. Some basic HTML tags—paragraph and strong—are added to give the generated page a bit of flair.

6. Print out the information of the user accessing the script:

echo "<p>You are viewing this page
Images using:<br><strong>$user</strong>
Images </p>
";

This line prints the second variable, $user. To repeat what’s said in the fourth step, $user correlates to $_SERVER[‘HTTP_USER_AGENT’] and refers to the operating system, browser type, and browser version being used to access the web page.

7. Print out the server information:

echo "<p>This server is running:
Images <br><strong>$server</strong>.
Images </p>
";

8. Complete the PHP block and the HTML page:

?>
</body>
</html>

9. Save the file as predefined.php, place it in your web directory, and test it in your browser Letter A in a circle..

Screenshot of predefined.php script in a browser tab is shown.

Letter A in a circle. The predefined.php script reports back to the viewer information about the script, the browser being used to view it, and the server itself.


Tip

If you have problems with this, or any other script, turn to the book’s corresponding forum (LarryUllman.com/forums/) for assistance.



Tip

If possible, run this script using a different browser and/or on another server Letter B in a circle..

Screenshot of predefined.php script in a browser tab is shown.

Letter B in a circle. This is the book’s first truly dynamic script, in that the web page changes depending on the server running it and the browser viewing it (compare with Letter A in a circle.).



Tip

Variable names cannot contain spaces. The underscore is commonly used in lieu of a space.



Tip

The most important consideration when creating variables is to use a consistent naming scheme. In this book you’ll see that I use all-lowercase letters for my variable names, with underscores separating words ($first_name). Some programmers prefer to use capitalization instead: $FirstName (known as “camel-case” style).



Tip

PHP is very casual in how it treats variables, meaning that you don’t need to initialize them (set an immediate value) or declare them (set a specific type), and you can convert a variable among the many types without problem.


Introducing Strings

Now that you’ve been introduced to the general concept of variables, let’s look at variables in detail. The first variable type to delve into is the string. A string is merely a quoted chunk of characters: letters, numbers, spaces, punctuation, and so forth. These are all strings:

Images ‘Tobias’

Images “In watermelon sugar”

Images ‘100’

Images ‘August 2, 2017’

To make a string variable, assign a string value to a valid variable name:

$first_name = 'Tobias';
$today = 'August 2, 2011';

When creating strings, you can use either single or double quotation marks to encapsulate the characters, just as you would when printing text. Likewise, you must use the same type of quotation mark for the beginning and the end of the string. If that same mark appears within the string, it must be escaped:

$var = "Define "platitude", please.";

Or you can instead use the other quotation mark type:

$var = 'Define "platitude", please.';

To print out the value of a string, use either echo or print:

echo $first_name;

To print the value of string within a context, you must use double quotation marks:

echo "Hello, $first_name";

You’ve already worked with strings once—when using the predefined variables in the preceding section, as the values of those variables happened to be strings. In this next example, you’ll create and use your own strings.

To use strings:

1. Begin a new PHP document in your text editor or IDE, to be named strings.php, starting with the initial HTML and including the opening PHP tag (Script 1.6):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Strings</title>
</head>
<body>
<?php # Script 1.6 - strings.php

Script 1.6 String variables are created and their values are sent to the browser in this script.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Strings</title>
6   </head>
7   <body>
8   <?php # Script 1.6 - strings.php
9
10  // Create the variables:
11  $first_name = 'Haruki';
12  $last_name = 'Murakami';
13  $book = 'Kafka on the Shore';
14
15  // Print the values:
16  echo "<p>The book <em>$book</em>
    was written by $first_name
    $last_name.</p>";
17
18  ?>
19  </body>
20  </html>

2. Within the PHP tags, create three variables:

$first_name = 'Haruki';
$last_name = 'Murakami';
$book = 'Kafka on the Shore';

This rudimentary example creates $first_name, $last_name, and $book variables that will then be printed out in a message.

3. Add an echo statement:

echo "<p>The book <em>$book
Images </em> was written by
Images $first_name $last_name.</p>";

All this script does is print a statement of authorship based on three established variables. A little HTML formatting—the emphasis on the book’s title—is thrown in to make it more attractive. Remember to use double quotation marks here for the variable values to be printed out appropriately (more on the importance of double quotation marks at this chapter’s end).

4. Complete the PHP block and the HTML page:

?>
</body>
</html>

5. Save the file as strings.php, place it in your web directory, and test it in your browser Letter A in a circle..

Screenshot of strings output screen is shown. The output screen reads “The book Kafka on the shore was written by Haruki Murakami.”

Letter A in a circle.The resulting web page is based on printing out the values of three variables.

6. If desired, change the values of the three variables, save the file, and run the script again Letter B in a circle..

Screenshot of strings output screen is shown in a browser tab. The output screen reads “The book Things Fall Apart was written by Chinua Achebe.”

Letter B in a circle.The output of the script is changed by altering the variables in it.


Tip

If you assign another value to an existing variable (e.g., $book), the new value will overwrite the old one. For example:

$book = 'High Fidelity';
$book = 'The Corrections';
/* $book now has a value of
'The Corrections'. */


Tip

PHP has no set limits on how big a string can be. It’s theoretically possible that you’ll be limited by the resources of the server, but it’s doubtful that you’ll ever encounter such a problem.


Concatenating Strings

Concatenation is like addition for strings, whereby characters are added to the end of the string. It is performed using the concatenation operator, which is the period ():

$city= 'Seattle';
$state = 'Washington';
$address = $city . $state;

The $address variable now has the value SeattleWashington, which almost achieves the desired result (Seattle, Washington). To improve upon this, you could write

$address = $city . ', ' . $state;

so that a comma and a space are concatenated to the variables as well.

Because of how liberally PHP treats variables, concatenation is possible with strings and numbers. Either of these statements will produce the same result (Seattle, Washington 98101):

$address = $city . ', ' . $state .
 ' 98101';
$address = $city . ', ' . $state .
 ' ' . 98101;

Let’s modify strings.php to use this new operator.

To use concatenation:

1. Open strings.php (refer to Script 1.6) in your text editor or IDE.

2. After you’ve established the $first_name and $last_name variables (lines 11 and 12), add this line (Script 1.7):

Script 1.7 Concatenation gives you the ability to append more characters onto a string.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Concatenation</title>
6   </head>
7   <body>
8   <?php # Script 1.7 - concat.php
9
10  // Create the variables:
11  $first_name = 'Melissa';
12  $last_name = 'Bank';
13  $author = $first_name . ' ' .
    $last_name;
14
15  $book = 'The Girls' Guide to Hunting and Fishing';
16
17  //Print the values:
18  echo "<p>The book <em>$book</em> was
    written by $author.</p>";
19
20  ?>
21  </body>
22  </html>

$author = $first_name . ' ' .
Images $last_name;

As a demonstration of concatenation, a new variable—$author—will be created as the concatenation of two existing strings and a space in between.

3. Change the echo statement to use this new variable:

echo "<p>The book <em>$book</em>
Images was written by $author.</p>";

Since the two variables have been turned into one, the echo statement should be altered accordingly.

4. If desired, change the HTML page title and the values of the first name, last name, and book variables.

5. Save the file as concat.php, place it in your web directory, and test it in your browser Letter A in a circle..

Screenshot of concatenation output screen is shown. The output screen reads “The book The Girls’ Guide to Hunting and fishing was written by Melissa Bank.”

Letter A in a circle.In this revised script, the end result of concatenation is not apparent to the user.


Tip

PHP has a slew of useful string-specific functions, which you’ll see over the course of this book. For example, to calculate how long a string is (how many characters it contains), use strlen():

$num = strlen('some string'); // 11


Tip

You can have PHP convert the case of strings with strtolower(), which makes it entirely lowercase; strtoupper(), which makes it entirely uppercase; ucfirst(), which capitalizes the first character; and ucwords(), which capitalizes the first character of every word.



Tip

If you are merely concatenating one value to another, you can use the concatenation assignment operator (.=). The following are equivalent:

$title = $title . $subtitle;
$title .= $subtitle;


Tip

The initial example in this section could be rewritten using either

$address = "$city, $state";

or

$address = $city;
$address .= ',';
$address .= $state;


Introducing Numbers

In introducing variables, I stated that PHP has both integer and floating-point (decimal) number types. In my experience, though, these two types can be classified under the generic title numbers without losing much valuable distinction. Valid numbers in PHP can be anything like

Images 8

Images 3.14

Images 10980843985

Images –4.2398508

Images 4.4e2

Notice that these values are never quoted—quoted numbers are strings with numeric values—nor do they include commas to indicate thousands. Also, a number is assumed to be positive unless it is preceded by the minus sign ().

Along with the standard arithmetic operators you can use on numbers (Table 1.1), dozens of functions are built into PHP. Two common ones are round() and number_format(). The former rounds a decimal to the nearest integer:

TABLE 1.1 Arithmetic Operators

Operator

Meaning

+

Addition

Subtraction

*

Multiplication

/

Division

%

Modulus

+ +

Increment

––

Decrement

$n = 3.14;
$n = round($n); // 3

It can also round to a specified number of decimal places:

$n = 3.141592;
$n = round($n, 3); // 3.142

The number_format() function turns a number into the more commonly written version, grouped into thousands using commas:

$n = 20943;
$n = number_format($n); // 20,943

This function can also set a specified number of decimal points:

$n = 20943;
$n = number_format($n, 2); //
20,943.00

To practice with numbers, let’s write a mock-up script that performs the calculations you might use in an e-commerce shopping cart.

To use numbers:

1. Begin a new PHP document in your text editor or IDE, to be named numbers.php (Script 1.8):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Numbers</title>
</head>
<body>
<?php # Script 1.8 - numbers.php

Script 1.8 The numbers.php script performs basic mathematical calculations, like those used in an e-commerce application.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Numbers</title>
6   </head>
7   <body>
8   <?php # Script 1.8 - numbers.php
9
10  // Set the variables:
11  $quantity = 30; // Buying 30 widgets.
12  $price = 119.95;
13  $taxrate = .05; // 5% sales tax.
14  
15  // Calculate the total:
16  $total = $quantity * $price;
17  $total = $total + ($total * $taxrate); // Calculate and add the tax.
18  
19  // Format the total:
20  $total = number_format ($total, 2);
21  
22  // Print the results:
23  echo '<p>You are purchasing <strong>' .
    $quantity . '</strong> widget(s) at a
    cost of <strong>$' . $price . '</strong>
    each. With tax, the total comes to
    <strong>$' . $total . '</strong>.</p>';
24  
25  ?>
26  </body>
27  </html>

2. Establish the requisite variables:

$quantity = 30;
$price = 119.95;
$taxrate = .05;

This script will use three hard-coded variables on which calculations will be made. Later in the book, you’ll see how these values can be dynamically determined (i.e., by user interaction with an HTML form).

3. Perform the calculations:

$total = $quantity * $price;
$total = $total + ($total *
Images $taxrate);

The first line establishes the order total as the number of widgets purchased multiplied by the price of each widget. The second line then adds the amount of tax to the total (calculated by multiplying the tax rate by the total).

4. Format the total:

$total = number_format($total, 2);

The number_format() function will group the total into thousands and round it to two decimal places. Applying this function will properly format the calculated value.

5. Print the results:

echo '<p>You are purchasing
Images <strong>' . $quantity .
Images '</strong> widget(s) at a cost
Images of <strong>$' . $price .
Images '</strong> each. With tax, the
Images total comes to <strong>$' .
Images $total . '</strong>.</p>';

The last step in the script is to print out the results. The echo statement uses both single-quoted text and concatenated variables in order to print out the full combination of HTML, dollar signs, and variable values. You’ll see an alternative approach in the last example of this chapter.

6. Complete the PHP code and the HTML page:

?>
</body>
</html>

7. Save the file as numbers.php, place it in your web directory, and test it in your browser Letter A in a circle..

Screenshot of numbers output screen is shown. The screen reads “you are purchasing 30 widget(s) at a cost of $119.95 each. With tax, the total comes to $3,778.43.”

Letter A in a circle. The numbers PHP page (Script 1.8) performs calculations based on set values.

8. If desired, change the initial three variables and rerun the script Letter B in a circle..

Screenshot of numbers output screen is shown. The screen reads “you are purchasing 12 widget(s) at a cost of $3.62 each. With tax, the total comes to $46.70.”

Letter B in a circle. To change the generated web page, alter any or all of the three variables (compare with Letter A in a circle.).


Tip

PHP supports a maximum integer of around two billion on most platforms. With numbers larger than that, PHP will automatically use a floating-point type.



Tip

When dealing with arithmetic, the issue of precedence arises—the order in which complex calculations are made. While the PHP manual and other sources tend to list the hierarchy of precedence, I find programming to be safer and more legible when I group clauses in parentheses to force the execution order (see line 17 of Script 1.8).



Tip

Computers are notoriously poor at dealing with decimals. For example, the number 2.0 may actually be stored as 1.99999. Most of the time this won’t be a problem, but in cases where mathematical precision is paramount, rely on integers, not decimals. The PHP manual has information on this subject, as well as alternative functions for improving computational accuracy.



Tip

Many of the mathematical operators also have a corresponding assignment operator, letting you create a shorthand for assigning values. The line

$total = $total + ($total * $taxrate);

could be rewritten as

$total += ($total * $taxrate);


Tip

If you set a $price value without using two decimals (e.g., 119.9 or 34), you would want to apply number_format() to $price before printing it.



Tip

New in PHP 7 is the intdiv() function, which returns the integer quotient of a division:

echo intdiv(7, 3); // 2

Introducing Constants

Constants, like variables, are used to temporarily store a value, but otherwise, constants and variables differ in many ways. For starters, to create a constant, you use the define() function instead of the assignment operator (=):

define('NAME', value);

Notice that, as a rule of thumb, constants are named using all capitals, although this is not required. Most importantly, constants do not use the initial dollar sign as variables do (because constants are not variables).

A constant is normally assigned a scalar value, like a string or a number:

define('USERNAME', 'troutocity');
define('PI', 3.14);

And unlike variables, a constant’s value cannot be changed.

To access a constant’s value, like when you want to print it, you cannot put the constant within quotation marks:

echo "Hello, USERNAME"; // Won't work!

With that code, PHP literally prints Hello, USERNAME Letter A in a circle. and not the value of the USERNAME constant because there’s no indication that USERNAME is anything other than literal text. Instead, either print the constant by itself:

Screenshot of using echo output screen is shown. The output screen reads “Hello, USERNAME.”

Letter A in a circle. Constants cannot be placed within quoted strings.

echo 'Hello, ';
echo USERNAME;

or use the concatenation operator:

echo 'Hello, ' . USERNAME;

PHP runs with several predefined constants, much like the predefined variables used earlier in the chapter. These include PHP_VERSION (the version of PHP running) and PHP_OS (the operating system of the server). This next script will print those two values, along with the value of a user-defined constant.

To use constants:

1. Begin a new PHP document in your text editor or IDE, to be named constants.php (Script 1.9).

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Constants</title>
</head>
<body>
<?php # Script 1.9 - constants.php

Script 1.9 Constants are another temporary storage tool you can use in PHP, distinct from variables.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Constants</title>
6   </head>
7   <body>
8   <?php # Script 1.9 - constants.php
9
10  // Set today's date as a constant:
11  define('TODAY', 'April 23, 2017');
12
13  // Print a message, using predefined constants and the TODAY constant:
14  echo '<p>Today is ' . TODAY . '.<br>This server is running version <strong>' .
    PHP_VERSION . '</strong> of PHP on the <strong>' . PHP_OS . '</strong> operating
    system.</p>';
15
16  ?>
17  </body>
18  </html>

2. Create a new date constant:

define('TODAY', 'April 23, 2017');

An admittedly trivial use of constants, but this example will illustrate the point. In Chapter 9, “Using PHP with MySQL,” you’ll see how to use constants to store your database access information.

3. Print out the date, the PHP version, and operating system information:

echo '<p>Today is ' . TODAY .
Images'.<br>This server is running
Imagesversion <strong>' . PHP_VERSION .
Images'</strong> of PHP on the
Images<strong>' . PHP_OS . '</strong>
Imagesoperating system.</p>';

Since constants cannot be printed within quotation marks, use the concatenation operator in the echo statement.

4. Complete the PHP code and the HTML page:

?>
</body>
</html>

5. Save the file as constants.php, place it in your web directory, and test it in your browser Letter B in a circle..

Screenshot of constants output screen is shown. The output screen reads “Today is April 23, 2017. This server is running version 5.6.30 of PHP on the Darwin operating system.”

Letter B in a circle. By making use of PHP’s constants, you can learn more about your PHP setup.


Tip

If possible, run this script on another PHP-enabled server Letter C in a circle..

Screenshot of constants output screen is shown. The output screen reads “Today is April 23, 2017. This server is running version 5.5.9-1ubuntu4.21 of PHP on the Linux operating system.”

Letter C in a circle. Running the same script (refer to Script 1.9) on different servers garners different results.



Tip

The operating system called Darwin Letter B in a circle. is the technical name for macOS.



Tip

In Chapter 12, “Cookies and Sessions,” you’ll learn about another constant, SID (which stands for session ID).



Tip

As of PHP 7, you can now create an array constant. You’ll learn more about arrays in Chapter 2, “Programming with PHP.”


Single vs. Double Quotation Marks

In PHP, it’s important to understand how single quotation marks differ from double quotation marks. With echo and print, or when assigning values to strings, you can use either, as in the examples used so far. But there is a key difference between the two types of quotation marks and when you should use which. You’ve seen this difference already, but it’s an important enough concept to merit more discussion.

In PHP, values enclosed within single quotation marks will be treated literally, whereas those within double quotation marks will be interpreted. In other words, placing variables and special characters (Table 1.2) within double quotes will result in their represented values printed, not their literal values. For example, assume that you have

$var = 'test';

TABLE 1.2 Escape Sequences

Code

Meaning

Double quotation mark

Single quotation mark

\

Backslash

Newline

Carriage return

Tab

$

Dollar sign

The code echo “var is equal to $var”; will print out var is equal to test, but the code echo ‘var is equal to $var’; will print out var is equal to $var. Using an escaped dollar sign, the code echo “$var is equal to $var”; will print out $var is equal to test, whereas the code echo ‘$var is equal to $var’; will print out $var is equal to $var Letter A in a circle..

Screenshot of using echo output screen is shown. The output screen reads “var is equal to test (double quotes). Var is equal to $var (single quotes). $var is equal to test (double quotes, escaped dollar sign). $var is equal to $var (single quotes, escaped dollar sign).

Letter A in a circle. How single and double quotation marks affect what gets printed by PHP.

As these examples should illustrate, double quotation marks will replace a variable’s name ($var) with its value (test) and a special character’s code ($) with its represented value ($). Single quotes will always display exactly what you type, except for the escaped single quote () and the escaped backslash (\), which are printed as a single quotation mark and a single backslash, respectively.

As another example of how the two quotation marks differ, let’s modify the numbers.php script as an experiment.

To use single and double quotation marks:

1. Open numbers.php (refer to Script 1.8) in your text editor or IDE.

2. Delete the existing echo statement (Script 1.10).

Script 1.10 This, the final script in the chapter, demonstrates the differences between using single and double quotation marks.


1   <!doctype html>
2   <html lang="en">
3   <head>
4      <meta charset="utf-8">
5      <title>Quotation Marks</title>
6   </head>
7   <body>
8   <?php # Script 1.10 - quotes.php
9
10  // Set the variables:
11  $quantity = 30; // Buying 30 widgets.
12  $price = 119.95;
13  $taxrate = .05; // 5% sales tax.
14  
15  // Calculate the total.
16  $total = $quantity * $price;
17  $total = $total + ($total * $taxrate); // Calculate and add the tax.
18  
19  // Format the total:
20  $total = number_format ($total, 2);
21  
22  // Print the results using double quotation marks:
23  echo "<h3>Using double quotation
    marks:</h3>";
24  echo "<p>You are purchasing
    <strong>$quantity</strong> widget(s)
    at a cost of <strong>$$price
    </strong> each. With tax, the total
    comes to <strong>$$total</strong>.
    </p>
";
25  
26  // Print the results using single quotation marks:
27  echo '<h3>Using single quotation
    marks:</h3>';
28  echo '<p>You are purchasing
    <strong>$quantity</strong> widget(s)
    at a cost of <strong>$$price
    </strong> each. With tax, the total
    comes to <strong>$$total</strong>.
    </p>
';
29  
30  ?>
31  </body>
32  </html>

3. Print a caption and then rewrite the original echo statement using double quotation marks:

echo "<h3>Using double quotation
Imagesmarks:</h3>";
echo "<p>You are purchasing
Images<strong>$quantity</strong>
Imageswidget(s) at a cost of
Images<strong>$$price</strong> each.
ImagesWith tax, the total comes to
Images<strong>$$total</strong>.</p>
";

In the original script, the results were printed using single quotation marks and concatenation. The same result can be achieved using double quotation marks. When using double quotation marks, the variables can be placed within the string.

There is one catch, though: trying to print a dollar amount as $12.34 (where 12.34 comes from a variable) would suggest that you would code $$var. That will not work (for complicated reasons). Instead, escape the initial dollar sign, resulting in $$var, as you see twice in this code. The first dollar sign will be printed, and the second becomes the start of the variable name.

4. Repeat the echo statements, this time using single quotation marks:

echo '<h3>Using single quotation
Images marks:</h3>';
echo '<p>You are purchasing
Images <strong>$quantity</strong>
Images widget(s) at a cost of
Images <strong>$$price</strong> each.
Images With tax, the total comes to
Images <strong>$$total</strong>.</p>
';

This echo statement is used to highlight the difference between using single or double quotation marks. It will not work as desired, and the resulting page will show you exactly what does happen instead.

5. If you want, change the page’s title.

6. Save the file as quotes.php, place it in your web directory, and test it in your browser Letter B in a circle..

Screenshot of quotation marks screen shows quotes.php file opened.

Letter B in a circle. These results demonstrate when and how you’d use one type of quotation mark as opposed to the other.

7. View the source of the web page to see how using the newline character ( ) within each quotation mark type also differs.

You should see that when you place the newline character within double quotation marks it creates a newline in the HTML source. When placed within single quotation marks, the literal characters and n are printed instead.


Tip

Because PHP will attempt to find variables within double quotation marks, using single quotation marks is theoretically faster. If you need to print the value of a variable, though, you must use double quotation marks.

Because valid HTML often includes a lot of double-quoted attributes, it’s often easiest to use single quotation marks when printing HTML with PHP:

echo '<table class="data">';

If you were to print out this HTML using double quotation marks, you would have to escape all of the double quotation marks in the string:

echo "<table class="data">";


Tip

In newer versions of PHP, you can actually use $$price and $$total without preceding them with a backslash (thanks to some internal magic). In older versions of PHP, you cannot. To guarantee reliable results, regardless of PHP version, I recommend using the $$var syntax when you need to print a dollar sign immediately followed by the value of a variable.



Tip

If you’re still unclear as to the difference between the types, use double quotation marks and you’re less likely to have problems.


Basic Debugging Steps

Debugging is by no means a simple concept to grasp, and unfortunately, it’s one that is only truly mastered by doing. The next 50 pages could be dedicated to the subject and you’d still only be able to pick up a fraction of the debugging skills that you’ll eventually acquire and need.

The reason I introduce debugging in this somewhat harrowing way is that it’s important not to enter into programming with delusions. Sometimes code won’t work as expected, you’ll inevitably create careless errors, and some days you’ll want to pull your hair out, even when using a comparatively user-friendly language such as PHP. In short, prepare to be perplexed and frustrated at times. I’ve been coding in PHP since 1999, and occasionally I still get stuck in the programming muck. But debugging is a very important skill to have, and one that you will eventually pick up out of necessity and experience. As you begin your PHP programming adventure, I can offer the following basic but concrete debugging tips.

Note that these are just some general debugging techniques, specifically tailored to the beginning PHP programmer. Chapter 8, “Error Handling and Debugging,” goes into other techniques in more detail.

To debug a PHP script:

Images Make sure you’re always running PHP scripts through a URL!

This is perhaps the most common beginner’s mistake. PHP code must be run through the web server application, which means it must be requested via http://something. When you see actual PHP code instead of the result of that code’s execution, most likely you’re not running the PHP script through a URL.

Images Know what version of PHP you’re running.

Some problems will arise from the version of PHP in use. Before you ever use any PHP-enabled server, run a phpinfo.php script (see Appendix A) or reference the PHP_VERSION constant to confirm the version of PHP in use.

Images Make sure display_errors is on.

This is a basic PHP configuration setting (also discussed in Appendix A). You can confirm this setting by executing the phpinfo() function (just use your browser to search for display_errors in the resulting page). For security reasons, PHP may not be set to display the errors that occur. If that’s the case, you’ll end up seeing blank pages when problems occur. To debug most problems, you’ll need to see the errors, so turn this setting on while you’re learning. You’ll find instructions for doing so in Appendix A.

Images Check the HTML source code.

Sometimes the problem is hidden in the HTML source of the page. In fact, sometimes the PHP error message can be hidden there!

Images Trust the error message.

Another very common beginner’s mistake is to not fully read or trust the error that PHP reports. Although an error message can often be cryptic and may seem meaningless, it can’t be ignored. At the very least, PHP is normally correct as to the line on which the problem can be found. And if you need to relay that error message to someone else (like when you’re asking me for help), do include the entire error message!

Images Take a break!

So many of the programming problems I’ve encountered over the years, and the vast majority of the toughest ones, have been solved by stepping away from the computer for a while. It’s easy to get frustrated and confused, and in such situations, any further steps you take are likely to only make matters worse.

Review and Pursue

Each chapter ends with a “Review and Pursue” section where you’ll find questions regarding the material just covered and prompts for ways to expand your knowledge and experience on your own. If you have any problems with these sections, either in answering the questions or pursuing your own endeavors, turn to the book’s supporting forum (LarryUllman.com/forums/).

Review

Images What tags are used to surround PHP code?

Images What extension should a PHP file have?

Images What does a page’s encoding refer to? What impact does the encoding have on the page?

Images What PHP functions, or language constructs, can you use to send data to the browser?

Images How does using single versus double quotation marks differ in creating or printing strings?

Images What does it mean to escape a character in a string?

Images What are the three comment syntaxes in PHP? Which one can be used over multiple lines?

Images What character do all variable names begin with? What characters can come next? What other characters can be used in a variable’s name?

Images Are variable names case-sensitive or case-insensitive?

Images What is the assignment operator?

Images How do you create a string variable?

Images What is the concatenation operator? What is the concatenation assignment operator?

Images How are constants defined and used?

Pursue

Images If you don’t already know—for certain—what version of PHP you’re running, check now.

Images Look up one of the mentioned string functions in the PHP manual. Then check out some of the other available string functions listed therein.

Images Look up one of the mentioned number functions in the PHP manual. Then check out some of the other available number functions listed therein.

Images Search the PHP manual for the $_SERVER variable to see what other information it contains.

Images Create a new script, from scratch, that defines and displays the values of some string variables. Use double quotation marks in the echo or print statement that outputs the values. For added complexity, include some HTML in the output. Then rewrite the script so that it uses single quotation marks and concatenation instead of double quotation marks.

Images Create a new script, from scratch, that defines, manipulates, and displays the values of some numeric variables.

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

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