COM372: Notes, Chapter 1

PHP Crash Course
pages 13-57

Syllabus | Grading | Reading Notes | Dr. Logan

Overview: This chapter gives a quick look at what is covered more thoroughly in chapters 2-7. It will help orient you if you are familiar with another programming language. If not, scan the chapter to get a notion of what will then be better explained in the rest of the book. The chapter builds an example using a form and a page to process information input on the form, the way all client-server exchanges begin. It does not use a database, yet.

Using PHP: PHP is a server technology. It parses the text written in PHP language that is embedded in a web page. The page is given a "php" file extension (instead of, say, "html"), which is enough to cause the server to look for the presense of php code within the page. The server must have php available. You can download a copy of the php engine for free following appendix A. Or, you can upload your php page to a php-supporting server, such as the course server, and run the page by calling it with a browser. The rest of the book assumes you know how to do this (as will have been explained in class).

XHTML Forms

XHTML <form> element. The development of the Bob's Auto Parts form (beginning on page 14) illustrates the two sides of xhtml forms, a form page to collect inputs, and a process page that uses them. Forms and the retrieval of information from them is XHTML technology, independent of server technologies like PHP; if you need information on forms, their elements, or various form attributes, etc., consult references on XHTML (see syllabus for COM271) Information is passed from the form page to the processing page. The form specifies the processing page in the form's action attribute. Information on the form is passed in either of two ways, determined by the form's method attribute. If method is GET, the information is appended to the url of the processing page (it is visible in the browser address window); if it is POST, the information is passed in an "HTTP header" which precedes the HTML page itself (and it is invisible to the user). Because the post method hides information—making it good for sensitive information like names, passwords, or financial information—and allows large amounts of information to be passed, it is generally the preferred method. The get method produces visible additions to the querystring, making it preferred for program debugging; also, if the information is appended to the URL, it can be saved (e.g., bookmarked), allowing a user to return directly to the form processing page without refilling the form.

Code for the form to collect information is on page 15. The form element is

<form action="processorder.php" method="post">form content here</form>,

and the elements (<input>, <select>, etc.) of the form are contained by it. The example uses two types of input elements, type="text" for the user to enter information and type="submit", which creates a button for the user to click on, processing the form (i.e., linking to the page on the server indicated in the "action" attribute.

Processing form information. When the user submits the form (by clicking on the submit button), information is passed to the processing page (the one you determined by "action=..."). Form information is passed in "collections" in "name : value" pairs. If the form's method was post, the collection is the "form" (also referred to as the "http") collection; if method was get, the collection is "querystring." The "name" comes from the name attribute of each form input, as in <input type="textbox" name="firstname"... To read the information, you use one of three methods. The $_REQUEST method (e.g., $_REQUEST ( 'firstname') will look for a form collection for values associated with names (in this case the name "firstname") and if there isn't a name : value pair, it will look for a querystring collection; the $_POST method will look only in the form / http collection; and the $_GET method will look only in the querystring collection (page 23).

PHP on the Web Page

Embedded PHP tags: Just as client-side JavaScript is added to a web page by coding functions and little pieces of script throughout the page, PHP is usually integrated over much of the web page. Functions and subroutines can be concentrated in the document head section, but scripts are usually mingled with page elements. PHP scripts are set off with tags, using one of four styles (page 19):

  1. XML style: <?php script; ?>—preferred
  2. Short style: < script; ?>—requires enabling (see page 17)
  3. SCRIPT style: <SCRIPT LANGUAGE = 'php' > script; </SCRIPT>
  4. ASP style: <% script; %>—also requires enabling

PHP scripts all end with a semi-colon.

Whitespace: Whitespace (blanks, new lines / carriage returns, tabs) are ignored by the PHP engine, just as they are by XHTML browsers.

Comments: Comments are set off by /* and */. Comments added to the end of a line can also use // or #. Comments are ignored by the PHP engine.

Echo: The echo function causes content to be written to the screen. Text is set off between single quotes, and the semicolon ends the line.

Date: The built-in date function (page 21) returns date and time, which can be output to the screen using echo. Date is called by its name followed by a pair of parentheses: date(); this is how all PHP functions, including ones you will build, are called.

Back to the Form...

Variable styles. PHP variables begin with a dollar sign, $. You can retrieve form field values using three styles of variables:

  1. short ($firstname)
  2. medium ($_POST('firstname'))
  3. long (($HTTP_POST_VARS('firstname'))

The long style is too long to type and will be deprecated, so don't use it. The medium style is recommended. The short style requires a server setting (something you can't do unless you are a server administrator). If set, names and values will be available to the page without you having to do anything else (see Variable Scope, below) . See page 23 for notes on why this makes you vulnerable to security problems.

Bottom line: Use the medium style.

To use form variables (pages 23-25), you can obtain them (i.e., get the value of whatever was passed using $_REQUEST, $_POST, or $_GET) and assign them to a shorter variable name, which you will use in the rest of your code

$first_name = $_GET('firstname')

/* Now do something with the variable $first_name */
If you are new to programming, the equal sign here isn't a mathematical term; it is called the "assignment" operator, and it means that the value of the variable on the right is "assigned" to the variable on the left (i.e., it is stored under that name). The variables may then be used on the screen using echo, as
<?php echo '<p>Hello, '.$firstname.'.</p>';

String Concatenation: Text strings (1 or more characters) can be joined end-to-end (concatenated) using a dot operator. Strings can be single-quoted text, string variables, or a combination; use of double quotations allows concatenation of variables and text. Text, which is actual content data, is also referred to as literal, in contrast to variable. (A third means to quote characters, the "heredoc" syntax, allows capture of long strings—see page 27). Here are two acceptable means to join strings and string variables:

PHP Variables

Variables: Variables have four characteristics:

  1. space in the computer's memory
  2. name
  3. value
  4. type

The name (="identifier") can be of any length. It is made up of letters, numbers, or underscores, but cannot begin with a number. PHP identifiers are case sensitive (var, VAR, and Var are different). You do not have to declare a variable before you use it (something you may do in other computer languages); it is created when you first assign a value to it. You assign values by placing the variable to the left of an equals sign ("assignment operator") and a literal or previously assigned variable (i.e., one that has something assigned to it, and thus has a value) to the right of the equals sign (e.g., $myname = 'Joe';)

Variable Type: There are different kinds of data; kinds are referred to as types. Types include

PHP data are weakly typed. Type is determined by the kind of data that is assigned to the variable. If a different kind of data is later assigned to the same variable name, that variable's type changes(!).(page 29)

Type cast: A variable that is to be assigned a value (i.e., one that is on the left side of the equals sign) can be assigned a different type than the type of the variable on the right side of the assignment by using a type cast. For example, $Sum = (float)$IntTotal will creat a variable of type float, and assign it the numerical value that is held in the integer IntTotal.

Constants: A variable may be made constant and given an (unchangeable) value through the define function, define ($_pi, 3.14159).

Variable Scope: All form name : value pairs are passed to the processing page in either the form or the querystring collections (i.e., the arrays $GLOBALS, $_GET, and $_POST). PHP gives these collections, organized as arrays, a superglobal scope. This allows you to "see" the variable from anywhere on the processing page, including within functions. Scope refers to visibility. Page 29 lists six rules to establish levels of scope—variations on superglobal, global, and local. Superglobal variables (the form collections) are visible everywhere. Global constants are also visible everywhere. Global variables declared in a script are visible everywhere except within functions. Global variables declared in a function refer to the global variables outside of the function by the same name. Static variables are declared within functions; these have local scope (are invisible outside of the function) and keep their value between calls to the function. Variables declared in the function but without global or static scope are used during the call to the function but loose their value outside of the function (they are local scope only). Scope is discussed in detail in chapter 5.

PHP Operators

Operators: Operators specify actions (i.e., they serve as verbs); operators act on variables. The assignment (=) and concatenation (.) operators put values into variables and join strings. Arithmetic operators perform arithmetic; they include additions (+), subtraction (-), multiplication (*), division (/), and modulus (%). Rules for precedence of subexpressions are discussed on page 35; they work the same in PHP as they do in normal mathematics.

Combination Assignment Operators: These provide a shorthand that affects the value of the variable on the left side of the assignment without having to write the same variable name on the right side. Instead of $a = $a + 5, you can write $a += 5. Similarly, you can use -=, *=, /=, %=, and .=. A second set allow for incrementing or decrementing a variable (adding or subtracting 1). This uses -- or ++ operators. If placed before the variable, the variable is incremented / decremented before the variable is used; if placed after the variable, the variable is used and afterwards incremented / decremented (page 35).

Referencing: Referencing (page 36) allows two variables to share an identical value. Assigning a new value to one also changes the value of the other. This is done with the reference operator (&), e.g., $a = &$b.

Comparison Operators: These operators compare two values, usually to decide what to do next in the code (conditional logic). The equals operator (==) checks for equality, returning true if the two variables have the same value, and false if they don't. Don't confuse this with the assignment operator (a single =)! A similar operator is identity (===), which checks both the value and the type of the two variables. Other comparison operators (table 1.3, page 37) include not equal (!= or <>), not identical (!==), less than (<), greater than (>), less than or equal to (<=) and greater than or equal to (>=)

Logical Operators: These are used to construct sets for logical evaluations. They include NOT (!), AND (&&), OR (||), and two lower precedence AND and OR operators (table 1.4, page 38).

Once more, Back to the Form...!

Doing the math: The example continues on page 41 with some typical arithmetic. The question of precedence and associativity is handled on pages 42-44; it follows standard approaches (multiplications and divisions are done before additions or substrations; operations are done on the innermost set of parentheses first, etc.). Study this section if these terms are new to you.

Variable functions: Built-in PHP functions allow you to determine the type or aspects of the status of a variable (pages 44-46). The gettype function returns a string telling you the type of a variable ($strtype = gettype ($myvariable)); settype changes type (settype ($myvariable, mynewtype). Other type-testing functions include is_array(), is_double() (same as is_float() and is_real()), is_long() (same as is_int() and is_integer()), is_string(), is_object(), is_null, is_numeric(), and is_callable() (tests whether the variable is a function name). A variable's status can be checked with isset (i.e., has a value), unset (deletes the variable!), or empty (checks whether a variable exists and has a nonempty nonzero value).

Control Structures ("Conditionals")

If: An IF statement evaluates a condition; if true, a statement or block of statements (set off with { } ) is executed. For example,

If ($firstname == 'Andy')
echo 'Good morning, Andrew.'


-or-

If NOT ($firstname == 'Andy')
{
echo '<p>I am sorry. I do not think I know you.</p>';
echo '<p>Please log in!</p>';
}

Else: This is combined with an if statement and a statement or block of code for when the condition is true; after the "true" block, the else statement precedes a statement of block of statements for when the condition is false.

Elseif: If there are more than two possible options, the else statement can be replaced with as many elseif statements as are needed to cover each option. Each condition will be tested until one is found to be true. You can use elseif or else if; both are correct.

Switch: This resembles the elseif statement. Switch takes as a condition any simple integer, string, or float. For each possible value of the condition, a case statement and block of code is provided, plus a default case and block of code. The value of the condition is compared with each case, and the block of code for which the case has a match is executed. See the example at the end of these chapter one notes.

Iterations (Loops and Branches)

While loops: A while resembles an if statement in that it evaluates a condition and a line or block of code is executed if the condition is true. Whiles differ from if statements in that the code is executed repeatedly until the condition becomes false. That implies that the condition is changing and being reevaluated once for each interation of the code block. The example on page 53 is a while loop to display numbers 1-5. Here, we'll display 1-100 with the same amount of code:

$inc = 1;
while ($num <= 100 )
{
  echo $inc."<br />"
  $inc++;
}

The example on page 54 illustrated use of a while loop to set up rows in a table, a common usage.

For and foreach loopsThe for loop runs off of a loop counter. Starting, ending, and increments for the counter are set; the loop also contains a block of code. Beginning with the starting value, the loop tests to see if the ending condition is met. If not, the starting value is incremented by the amount of the increment value and the code block is executed once. Here's the same display of numbers 1-100 using a for loop:

for ($icount = 1; $icount <= 100; $icount += 1;)
echo '<p>'. $icount.'</p>';

The foreach loop is used with arrays (chapter 3)

Do...while loops: The do...while loop executes a block of code first, and then tests a condition to see whether the loop is executed again. The form is

do
expression;
while (condition);

Alternative loop syntax: For if statements or loops, the brackets around the block of code statements can be replaced with a preceeding colon and a trailing endif;, endswitch;, endwhile;, endfor;, or endforeach; (page 56).

Programming Suggestions

1.) Form submission and processing on the same page: The form's action attribute can use an appended name:value pair to include information that can be used to determine an option in a switch. This can be used to put both a form and its response on the same page, or even more. The following provides a structure for choosing a record from a database, altering the record, and displaying the changes prior to finalizing changes in the database, all on the same page. The details of the code will be filled in subsequent chapters. The page is named "update_list.php." Note that although this page will be relatively long, only the relevant section (case) is turned into html to be sent to the client. The advantage is that as a programmer, you don't have to keep track of two or three corresponding pages.

...html header section
<body>
<?php

$action = $_POST('what_to_do');
if $action == ""
$action = 'choose_record'

switch ($action):

case 'choose_record' :
{
/*a form to display a dropdown list of records (e.g., first and last names to choose)*/
<form method="get action="update_list.php?what_to_do=alter_record">
/* rest of form to choose a record... */

case 'alter_record'
/* now a form to let the user change the selected record... */
<form method="get" action="update_list.php?what_to_do=confirm_changes">
rest of form to enter changes...

case 'confirm_changes'
/* code to display and confirm changes and to update the database */

endswitch;
?>
</body>

2) Mixing HTML and PHP modes: "One of the great benefits of PHP is the ability to embed PHP code in to an HTML page, and to jump into and out of PHP mode at will. However, this needs to be done with care to the appearance of the resulting code. You should not be constantly opening and closing PHP code blocks to just insert a couple lines of text. In these cases, itoften makes for clearer code to use echo statements to write the code to the screen. If needed this could even be done via multiline strings or by using the heredoc syntax. More on these options can be found at http://php.net/string.
In general us your common sense. Try to make code as legible as possible." (White and Eisenhamer. 2007. PHP 5 in Practice: Recipes and solutions for PHP programmers. Sam's Publishing. 440p. )