Search This Blog

Sunday, January 31, 2010

Accessing PHP and HTTP Data

You know how HTTP works and you basically understand clients and servers, so you're very cognizant of the interaction between your browser (a client application) and the Web server (a server application) when running PHP programs online. In this chapter you explore HTML forms and examine how they facilitate user interactions with the Web server (and thereby your PHP programs). These topics deserve a lot of attention because HTTP, HTML, and PHP are tightly intertwined. A good understanding of what's going on between the browser and the server is essential for PHP programming because within the requests and responses flying back and forth from client to server is a wealth of data you can utilize.

Each time you click a link or submit a form, you send a great deal of data about your system and your browser to the Web server, and each time the Web server responds, it sends you a great deal of data about itself. PHP has the capability to capture the data that is submitted by a browser, and also provides a means of getting at data about PHP's installation on the server. For instance, if you go to your favorite PHP-driven Web site and log in, it's likely that a predefined variable named $_POST is filled (on the server) with your username and password, another predefined variable named $_SERVER contains information about the current Web server environment, and that both are available to the PHP application running the site. These aspects of PHP are discussed in depth in the next few sections, but it's really kind of surprising how much data is available (especially considering that most folks aren't even aware of it). Read on to learn how to access all this data.

Predefined Variables

PHP automatically makes quite a few variables (called predefined variables) available anywhere in your program. They are array variables, and you can access them by name, like any other variable. By default, PHP is configured not to populate these variables (in the php.ini file, the default register_globals=Off is in place), you must use their entire name to access their data. For example, if a form has a text field named username and this field is filled out and submitted (and assuming the form's submission method is POST), you can access the field's data by code such as this:

$my_new_username = $_POST[username];
Predefined variables are also called superglobal variables because they can be accessed without regard to scope. Predefined variables consist of most of the information contained in HTTP requests and responses, including server variables, query strings, form variables, and so on. You can use predefined variables for any purpose, just like ordinary variables, but some of them may or may not be present for any given installation of PHP because Web servers vary in the data provided via HTTP. In the next section you'll see how to retrieve the data in predefined variables.

In addition to predefined variables, you can use the built-in PHP function phpinfo() to get basic PHP installation and operating information. This function not only enables you to test whether PHP is installed and working (as you saw in Chapter 1), but also enables you to find out many details about how PHP is installed on the server. For example, you can find out what version of PHP is running, what OS your server is running on, and so forth.
Perhaps an easier way to demonstrate what you get from the phpinfo() function is simply to run the test01.php file created in Chapter 1 again. This time you're running it not just to see if the installation of PHP worked (as you did in Chapter 1) but to examine the various kinds of data it provides. When run from your Web server, phpinfo() creates a very nicely formatted and detailed page (including all the required HTML tags) describing the PHP version, operating system, version of the ZEND engine, settings in your php.ini file, additional modules, and predefined variables.

Variables in HTTP Request and Response

There's a surprising amount of data passed back and forth between the client and the Web server (and vice versa). For example, not only is the IP address of the client passed to the Web server with each request (not actually very surprising, as how else would the Web server know where to send the response) but also details about what version of browser is making the request, cookies, form data, Web server version, and so on. The data is contained in predefined variables structured as associative arrays, so that you can access them by name, just like you would access any other array. The contents of each and what you might want to use them for are presented after the following "Try It Out."

There is a setting in your configuration file (php.ini) called register_globals. The default is off (since PHP4.2), and it restricts how you can access some predefined variables. From a practical standpoint, this means you should use the full name of the array ($_SERVER['DOCUMENT-ROOT'] is the example given) to access data in predefined variables. There is the function (import_request_variables()) that will import GET, POST, and Cookie variables into the global scope, so you can access them directly by name, but the full array name is recommended and therefore used in this book.

Try it Out: Display $GLOBALS
Start example
The following code demonstrates displaying the contents of the $GLOBALS predefined variable. The code goes inside a nicely formatted HTML Web page:

<?php
echo "<pre>";
print_($GLOBALS);
echo "</pre>";
?>
Run this code in your browser (name the file displaying_predefined_vars.php) and you'll see what the $GLOBALS array contains. Don't be too surprised if they all turn out to be empty at the moment. However, at the end of this section is a figure showing what the predefined variables look like when displayed.

Don't forget to place the file in the appropriate folder that's published by your Web server. From here on out it's assumed that you've created any Web server-accessible folders you want and are placing your files in them as needed.
End example

How it Works

The print_r() function prints out information about variables in a format that is easy for people to read. It's especially useful with arrays because it prints the keys and values one after the other. Use it with the HTML <pre> tags so it prints nicely on the page, rather than all on one line.

SuperGlobal Arrays

The predefined arrays are described in the following table. They're called superglobals because they can be accessed form anywhere in a PHP program without having to use the global keyword and without regard for scope.

Array
Description
$GLOBALS
Has a reference to every variable that has global scope in a PHP program. Many of the variables in it are also in other superglobal arrays
$_SERVER
Includes everything sent by server in the HTTP response, such as the name of the currently executing script, server name, version of HTTP, remote IP address, and so on. Although most Web server software produces the same server variables, not all do, and not all server variables necessarily have data in them
$_GET
Contains all the querystring variables that were attached to the URL, or produced as a result of using the GET method
$_POST
Contains all the submitted form variables and their data. You use variables from the $_POST or $_REQUEST arrays extensively in most of your PHP programs. For example, to make use of a username or password (or any other data) submitted as part of a form, you'll use PHP variables from the $_REQUEST array
$_COOKIE
Contains all cookies sent to the server by the browser. They are turned into variables you can read from this array, and you can write cookies to the user's browser using the setcookie() function. Cookies provide a means of identifying a user across page requests (or beyond, depending upon when the cookie expires) and are often used automatically in session handling
$_FILES
Contains any items uploaded to the server when the POST method is used. It's different from the $_POST array because it specifically contains items uploaded (such as an uploaded image file), not the contents of submitted form fields
$_ENV
Contains data about the environment the server and PHP are operating in, such as the computer name, operating system, and system drive
$_REQUEST
Contains the contents of the $_GET, $_POST, and $COOKIE arrays, all in one
$_SESSION
Contains all variables that are currently registered as session variables. Because you have programmatic control over the variables registered in the session, the contents of this array at any given moment depend on what your program does and whether you use sessions
The following code makes a page showing the contents of the SuperGlobal variables just discussed. If you look closely at the code, you'll notice that much of it is the same thing over and over; that's because each variable (with a bit of HTML thrown in for formatting) is being displayed. Save the code as displaying_predefined_vars.php before running it from your browser:

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor= " #FFFFFF" >
<table width="100%" border="1">
  <tr><td colspan="2"><font face="Arial, Helvetica, sans-serif" size=
"-1"><b>Displaying Predefined Variables</b></font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1">Globals - $GLOBALS</font></td>
    <td width="60%"><font face="Arial, Helvetica, sans-serif" size="-2">
<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>
</font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1">Server - $_SERVER</font></td>
    <td width="60%"><font face="Arial, Helvetica, sans-serif" size="-1">
<?php
echo "<pre>";
print_r($_SERVER);
echo "</pre>";
?>
</font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1">Get - $_GET </font></td>
  <td width="60%"><font face="Arial, Helvetica, sans-serif" size="-1">
<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
?>
</font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1">Post - $_POST </font></td>
    <td width="60%"><font face="Arial, Helvetica, sans-serif" size="-1">
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
</font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1">Cookie - $_COOKIE</font></td>
    <td width="60%"><font face="Arial, Helvetica, sans-serif" size="-1">
<?php
echo "<pre>";
print_r ($_COOKIE) ;
echo "</pre>";
?>
</font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1">Files - $_FILES</font></td>
    <td width="60%"><font face="Arial, Helvetica, sans-serif" size="-1">
<?php
echo "<pre>";
print_r ($_FILES);
echo "</pre>";
?>
</font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1"> Environment - $_ENV</font></td>
    <td width="60%><font face="Arial, Helvetica, sans-serif" size="-1">
<?php
echo "<pre>";
print_r($_ENV);
echo "</pre>";
?>
</font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1">Request - $_REQUEST</font></td>
    <td width="60%"><font face="Arial, Helvetica, sans-serif" size="-1">
<?php
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
?>
</font></td>
  </tr>
  <tr><td width="40%" valign="top"><font face="Arial, Helvetica, sans-serif"
size="-1">Session - $_SESSION</font></td>
    <td width="60%"><font face="Arial, Helvetica, sans-serif" size="-1">
<?php
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
</font></td>
  </tr>
</table>
</body>
</html>

Saturday, January 30, 2010

HTML Primer

If you're an HTML wizard and have an in-depth understanding of the structure of HTML, you can probably skip this section, but for those of you who've never dissected HTML code or the HTML specification, read on. You'll recall that PHP's "middle name" is hypertext and that alone tells you that PHP is intertwined with HTML (Hypertext Markup Language). Understanding how HTML—particularly the HTML <form> element—works is very important to proficiency with PHP.

HTML was created by Tim Berners-Lee and Robert Caillau in 1989. It is a subset of Standard Generalized Markup Language (SGML). SGML was defined by International Standards in 1986 as ISO 8879:1986. SGML is designed to provide a common format for markup languages. HTML is called an SGML application because it is a language, whereas XML is simply a subset of the SGML specification used to make your own markup languages (more on XML in Chapter 8).

Like most SGML applications, HTML includes a Document Type Definition (DTD) that specifies the syntax of markup elements. You'll see examples of the HTML DTD throughout this primer.
The World Wide Web Consortium (W3C) can be found at www.w3.org. This organization maintains the HTML specification (now the XHTML specification). Visit the site and look for the HTML 4.01 specification to see all the elements and attributes.
HTML is a markup language, not a programming language. The primary purpose of HTML is to display data or content (such as text and images) along with hypertext links. HTML tags (the "commands" in HTML) help the Web page designer arrange the display of text, graphics, and multimedia. The only elements that give something resembling programmatic functionality are used to make tables, links, forms, and frames.

HTML is written in plain text, and when a page is requested all the code is sent in plain text format. Here's a simple HTML Web page (without a body):

<html>
<head>
<title>The Title</title>
</head>
</html>
Although the convention for many years was to write HTML tags uppercase (as in <HTML>), the HTML specification actually has no preference, and you can write conforming HTML tags either way, or even a mixture of upper and lower case (as in <hTmL>). However, the latest standard for HTML is now XHTML, which adheres to the XML specification, so there is a difference between uppercase and lowercase tags. XHTML specifies lowercase for tag names, which is why nearly every HTML tag in this book is lowercase. Browsers won't care whether the tags are uppercase or lowercase, but using lowercase will make it a lot easier to change your HTML to conform to XHTML.
An HTML Web page is made up of HTML tags, and most (but not all) of these tags have both beginning (opening) and ending (closing) tags. HTML tags are delimited by the angle brackets (<>). An HTML tag is named for the element it represents. For example, the tags <html> and </html> are the opening and closing tags for the HTML element. These tags signify the beginning and ending of the entire HTML document. Within these tags are the tags for the <head> of the document and for the title of the document. Tags contained within other tags are said to be nested.
 
Some HTML elements have only a beginning tag, such as the IMG element. When writing an IMG element (the IMG element inserts an external image file into a Web page) all you write is <img>, without en ending </img>. However, to tell the browser where to find the external image file, you place what is called an attribute in the beginning tag. HTML attributes are like fields in a database, or properties in an object, or variables in a program. They have names (such as SRC), and are containers for values. In fact, you set the value of the SRC attribute in the <img> tag to the URL of the image file name (like this: <img SRC="http://www.example.com/images/example.gif">). When the user's browser receives the HTML of the Web page, the browser reads the HTML, finds the URL of the image file, requests that file as well, and then inserts the file into the rendered Web page at the appropriate spot.

The HTML Document Type Definition

A DTD declares what elements and attributes (and a few other things) that are allowed in an HTML document. Although an HTML document is made up of HTML tags, the HTML DTD uses a special format to specify what elements and attributes you can use. For example, because the HTML DTD specifies an IMG element, you can use the IMG element in a Web page.

But it's still up to the maker of your browser to properly recognize and display elements and attributes specified in the HTML DTD. In fact, deviations from the HTML specification are the primary reason a Web page may look (and work) fine in one browser and not in another.
Technically, HTML documents should start with a line indicating the DTD to be used, contained within the <!DOCTYPE> element. The DOCTYPE declaration indicates to the browser the proper DTD to use, but the inclusion of this line is not enforced by browsers. Many Web pages have no DOCTYPE declaration, but are still rendered correctly in browsers. Here's a DOCTYPE declaration inserted by Dreamweaver (a popular Web page design tool):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

The Form and Input Elements

One of the primary HTML elements you'll be working with is the <form> element. Take a look at how it's specified in the HTML DTD:

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
<!ATTLIST FORM
  %attrs;                              -- %coreattrs, %i18n, %events --
  action      %URI;          #REQUIRED -- server-side form handler --
  method      (GET|POST)        GET    -- HTTP method used to submit the form --
  enctype     %ContentType;  "application/x-www-form-urlencoded"
  accept      %ContentTypes; #IMPLIED  -- list of MIME types for file upload --
  name        CDATA          #IMPLIED  -- name of form for scripting --
  onsubmit    %Script;       #IMPLIED  -- the form was submitted --
  onreset     %Script;       #IMPLIED  -- the form was reset --
  accept-charset %Charsets;  #IMPLIED  -- list of supported charsets --
  >
The DTD for <form>begins with a line that names it as an element, and then specifies a list of attributes (ATTLIST). Notice the action attribute, which tells the browser where to send the contents of the form, and the method attribute, which tells the browser how to send the contents of the form.

The <input> element makes text fields, radio buttons, check boxes, and so on in a form.

Here's its DTD:

<!ENTITY % InputType
  "(TEXT | PASSWORD | CHECKBOX |
    RADIO | SUBMIT | RESET |
    FILE | HIDDEN | IMAGE | BUTTON)"
   >
<!-- attribute name required for all but submit and reset -->
<!ELEMENT INPUT - o EMPTY             -- form control -->
<!ATTLIST INPUT
  %attrs;                             -- %coreattrs, %i18n, %events --
  type        %InputType; TEXT        -- what kind of widget is needed --
  name        CDATA          #IMPLIED -- submit as part of form --
  value       CDATA          #IMPLIED -- Specify for radio buttons and
checkboxes
--
  checked     (checked)      #IMPLIED -- for radio buttons and check boxes --
  disabled    (disabled)     #IMPLIED -- unavailable in this context --
  readonly    (readonly)     #IMPLIED -- for text and passwd --
  size        CDATA          #IMPLIED -- specific to each type of field --
  maxlength   NUMBER         #IMPLIED -- max chars for text fields --
  src         %URI;          #IMPLIED -- for fields with images --
  alt         CDATA          #IMPLIED -- short description --
  usemap      %URI;          #IMPLIED -- use client-side image map --
  ismap       (ismap)        #IMPLIED -- use server-side image map --
  tabindex    NUMBER         #IMPLIED -- position in tabbing order --
  accesskey   %Character;    #IMPLIED -- accessibility key character -
  onfocus     %Script;       #IMPLIED -- the element got the focus --
  onblur      %Script;       #IMPLIED -- the element lost the focus --
  onselect    %Script;       #IMPLIED -- some text was selected --
  onchange    %Script;       #IMPLIED -- the element value was changed --
  accept      %ContentTypes; #IMPLIED -- list of MIME types for file upload --
  >
The type attribute of the element specifies the type of control that will appear on the screen in your browser (text makes a text field, radio makes a radio button, and so on).
To create a Web page with a form in it, you could write the following HTML code in plain text, upload it to a Web server (or even just open it directly in your browser), and it would display as a nicely formatted Web page:

<html>
<head>
<title>
</title>
</head>
<body bgcolor="white">
<form method="post" action="http://www.example.com">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
This code creates a simple form with two fields (username and password) and a submit button. When submitted, the form's contents are sent to www.example.com.

How can you make HTML forms and PHP work together to make Web pages that are dynamically generated (rather than simply copied to your browser by the Web server)? First, you create a Web page using plain text HTML tags, and include an HTML form within that page. Then, you write PHP code within the Web page, making sure the code is properly enclosed by the <?php and ?> delimiters.

When the Web page is requested by a browser, any PHP code in it is resolved or processed by the PHP scripting engine before the results are returned to the user, and the results of PHP processing are placed in exactly the same spot as the original PHP code. You also could write your code so that it is only processed when there is a form submission (you'll see how in the next few sections). It may even use some of the submitted form data in its processing.

The end result of the PHP processing is HTML compatible, but because the PHP scripting engine has a chance to perform some processing before the final version of the Web page is sent, some of the content of the page (any parts generated by the PHP code) may differ each time the page is requested. And if processing takes place in response to a form submission, there are a great variety of interactive features that can be created.

Friday, January 29, 2010

Chapter 3: PHP, HTML, and State

By now you're familiar with HTTP, simple PHP programs, variables, and some of the PHP built-in functions, and although you can do a lot with what you've already learned, there's a key ingredient missing: user interaction! That's what this chapter is all about, at least as far as Web-based applications are concerned.

If you remember back before 1994 (a million years ago in Web time), early Web pages consisted of text, images, and links. The backgrounds were gray; there were no tables (much less DHTML and style sheets) to help structure pages; and there was little user interaction. The introduction of HTML elements for forms and form fields opened the door to direct, form-based interaction between the user and the Web server. HTML forms are today one of the most used (and most useful) means for interacting with online applications.

You'll explore HTML forms, but you'll also learn what kinds of data are available in HTTP requests and responses, and how you can use PHP to capture that data and then use it in your programs.

You'll examine the specifics of talking to the Web server (using the GET and POST methods), the format of requests and responses sent between client and server (and all the great data you can extract from them), and the nature of applications running across the Internet. You'll look at the concept of state, the lack of state in HTTP Web communications, and several methods for working around that deficiency. You'll get a look at PHP sessions as well.

Thursday, January 28, 2010

Operators and Expressions

Processing data is accomplished in PHP, as it is in other programming languages, by way of operators and expressions. Operators are the symbols that tell PHP what operations to perform, and expressions are the individual sets of variables and operators that make a result when processing is complete.

PHP Operators

In PHP, you create a variable and set a value to it by using the equal sign, as in:

$my_data = "Hello";
The equal sign is an operator. Operators are used to perform data processing on variable values. In this case, the equal sign is called the assignment operator, because it assigns the string data value to the variable just created.

There are quite a few operators in most programming languages; some of them perform arithmetic, just like you would in a simple equation; some of them operate on string or date data; and some of them perform other functions. They all carry out data processing on variable values.


Important 
Operators that need only one operand are called unary operators; for example, the ++ operator can be appended to the end of a variable name (the operand) to increment the variable by one. Because the ++ operator can be placed before the variable or after the variable, it is said to allow both prefix and postfix notation.
Operators that need two operands are called binary operators; the equal sign used in "$my_data = "Hello" is one example. Because the operator is placed between the operands, it is said to be using infix notation.
And some languages contain tertiary operators requiring three operands. For example, PHP allows use of the ? operator, which is a shorthand If statement. Such a statement would begin with an expression followed by the question mark, then two possible outcomes separated by a colon ("expression. ? outcome02 : outcome02", meaning "if expression is true then do outcome01, but if not true then do outcome02"). Because the operator is inside the operands, it is also said to use infix notation.

PHP Expressions

Expressions are any code that evaluates to a value. The assignment of a value to a variable is an expression in itself, although we tend to think of expressions as similar to equations (like $a = $b + $c, where $b + $c is the expression we have in mind).

Therefore, $a = 5 is an expression, because it evaluates to the value 5. If you write $a = $b + $c, you know you're adding $b and $c first, and then setting $a equal to the resulting value. You can make expressions arbitrarily complex (as complex as you'd like) and you can use any of the operators on any appropriate values to get a result. In fact, the main portion of PHP functionality comes from its processing (evaluation) of expressions.

One key part of evaluating an expression, particularly complex expressions, is operator precedence. As in arithmetic or math, it sometimes makes a difference which part of an expression is evaluated first. There is a default precedence of operations, and you can directly control precedence by inserting parentheses. For example, because the multiplication operator (*) has precedence over the addition operator (+), the expression 2 + 2 * 12 results in a value of 26 (2 * 12 is evaluated first, by default, and then added to 2), whereas (2 + 2) * 12 results in a value of 48 (the parentheses force 2 + 2 to be added together first, then the result of that is multiplied by 12).

Operator Types

The following operator types are available in PHP:

Type
Description
Arithmetic
Perform common arithmetical operations, such as addition and subtraction
Assignment
Assign values to variables
Bitwise
Perform operations on individual bits in an integer
Comparison
Compare values in a Boolean fashion (true or false is returned)
Error Control
Affect error handling (several new ones in PHP5)
Execution
Cause execution of commands as though they were shell commands
Incrementing/Decrementing
Increment or decrement a variable
Logical
Boolean operators such as AND, OR, and NOT that can be used to include or exclude (more on this in Chapter 4)
String
Concatenates (joins together) strings
Array
Perform operations (such as append or split) on arrays
An exhaustive list and reference for each operator aren't provided here because that information is easily available online at www.php.net (just go to the site, click documentation, and you'll find operators listed in the table of contents). When an operator is used in this book, though, some of its peculiarities are discussed.

String Operators and Functions

There is only one string operator: the dot (.), but PHP contains plenty of string functions that enable you manipulate strings effectively. The following sections discuss how the concatenation operator and several of the string functions work.
Using the Concatenation Operator
The concatenation operator (.) can be used between string values to join them together. Here's how it's done in a PHP program:

<?php
$first_name = "Joe";
$last_name = "Blow";
$whole_name = $first_name . " " . $last_name;
echo "First name plus last name = <b>$whole_name</b>";
?>
Notice that a space is added to the $whole_name value by concatenating " " (a space between quotes) into the $first_name and $last_name values. There's also a space before and after the concatenation operator each time it's used. This is not necessary, but makes the code a little easier to read. The following code would work just as well:

$whole_name = $first_name." ".$last_name;
To make the answer more readable when displayed in the Web page, HTML tags are added to the echoed response (the <b> and </b> tags to make text bold):

echo "First name plus last name = <b>$whole_name</b>";
Unless you need to include special characters such as quotes in your HTML, you can simply insert the HTML into your text, which will be properly formatted by the browser when the page is displayed. As you can see, the variable $whole_name was simply inserted right into the line of code. In many programming languages it's not possible to do this, but PHP is smart enough to understand that when you use a variable name in a string you want its value—not its name—placed in the string. Of course, if you want the name to be displayed in the string, you must escape the dollar sign (precede the dollar sign with a slash) so PHP knows not to insert the value:

echo "First name plus last name = <b>\ $whole_name</b>";
Using the strien() function
The strlen () function finds the length of a string. It counts all characters in the string and returns the total. In the following example, the total number of characters is placed into the variable named $string_length:

$string_length = strlen($whole_name);
Interestingly, using the concatenation operator to join together a string (such as "The length of the name is") and a numerical value (such as the length of the string contained in $string_length) has the effect of making the entire response a string data type.

The string length function is useful whenever you need a count of the characters in a string, such as when validating data that might go into a database.
Using the strstr() function
The strstr () function gets any part of a string that is after the first instance of a particular character or string within a string. In the next example, the $whole_name variable value (Joe Blow) is searched until the first occurrence of the space character, and then the strstr () function returns everything after that space. Additional occurrences of the search string within the searched string make no difference whatsoever. If the string you seek isn't found within the string being searched, the function returns a value of FALSE.
 
$part_after_space = strstr($whole_name, " ");
echo "The part of the string after the space is <b>" .
$part_after_space . "</b>";
Using the strpos() function
The strpos () function is used to determine whether a search string exists within a searched string, and returns a numeric value indicating the location at which the search string begins, if found. In the following example, searching for the string o within the $whole_name value (Joe Blow), returns the position value "1". You might have expected to receive the number 2, because o is the second letter in the name, but like many other programming languages, PHP often uses sets of values starting with 0 rather than 1, so the location is specified as "1".

$letter_position = strpos($whole_name, "o");
echo "The position of the letter &quot;a&quot; is <b>" .
$letter_position . "</b>";
In this particular case, PHP is examining the string Joe Blow as though it were an array of characters (which, in fact, it is in PHP), and uses array index values (0,1,2,3,4, and so on) for the location of each character. (There's an "Arrays" section coming up in just a few pages.)
Using the chr() function
The chr () function returns a string character value corresponding to the decimal ASCII value entered as the argument. You can find tables of ASCII characters all over the Internet, and it is often convenient to use them, especially for special characters. For example, the ASCII character for a line feed is 10 and for a carriage return is 13. There really aren't keyboard characters you can enter for these characters, so if you need to include them in a string, you just use chr (10) and chr (13) and the alphabetic characters they represent are inserted into your string.

Try it Out: Work With Strings
Start example
Time to create some simple PHP programs that demonstrate how you can use operators in expressions with variables. This program demonstrates working with strings. You'll use the string operator, the dot (.), and several of PHP's built-in string functions. Here's what to do:
  1. Create a file in any text editor, and save it as working_with_strings.php. Place it in the folder supported by the Web server (if you're working on the machine running the Web server) or upload it to the appropriate folder on the Web server (and upload it again each time you make changes).
  2. Enter the following code in your file (the screen highlights the PHP portions of code):

    <html>
    <head>
    <title>Beginning PHP5</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body bgcolor="#FFFFFF">
    <table width="100%" border="1">
      <tr>
        <td width="49%"><font face="Arial,   Helvetica, sans-serif"><b>Working With
          Strings</b></font></td>
        <td width="51%">&nbsp;</td>
      </tr>
      <tr>
        <td width="49%"><font face="Arial, Helvetica, sans-serif" size="-1">Using
          Concatenation - the . operator</font></td>
        <td width="51%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $ first_name= "Joe";
    $last_name = "Blow" ;
    $whole_name = $first_name . " " . $last_name;
    echo "First name plus last name  = <b>$whole_name</b>" ;
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="49%"><font face="Arial,   Helvetica, sans-serif" size="-1">
    Finding
          String Length - using <b>strlen() </b></font></td>
        <td width="51%" ><font   face="Axial. Helvetica. sans-serif" size="-1">
    <?php
    $string_length = strlen ($whole_name) ;
    echo "The length of the name is <b>" . $string_length . "</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="49%"><font face="Arial, Helvetica, sans-serif" size="-
    1">Getting
          Part of a String - using <b>strstr()</b></font></td>
        <td width="51%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $part_after_space = strstr($whole_name, " ");
    echo "The part of   the  string after the space is <b>" . $part_after_space
    "</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="49%"><font face="Arial, Helvetica, sans-serif"
    size="-1">Finding
          Position of Part of a String - using <b>strpos()</b></font></td>
        <td width="51%"><font face="Arial, Helvetica, sans-serif" size="-1">
    php
    $letter_position = strpos($whole_name, "0");
    echo "The position of the letter &quot;o&quot; is <b>" . $letter_position .
    "</b>";
    ?>
    </font></td>
      </tr> 
      <tr>
        <td width="49%"><font face="Arial, Helvetica, sans-serif" size="-1">Return
          a character based on an ASCII value - using <b>chr()</b></font></td>
        <td width="51%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $ascii_character_returned = chr(97);
    echo "The character corresponding to ASCII decimal value 97 is <b>"
    . $ascii_character_returned . "</b>";
    ?>
    </font></td> </tr>
    </table>
    </body>
    </html>
  3. Save the file, upload it if required, and then display it in your browser.

End example

How it Works

The PHP program you just created is embedded in a complete HTML Web page, and within the HTML <body> element the parts of the program are contained within an HTML <table> purely for readability. When the Web page file is requested from the Web server by a browser, the PHP code is parsed and executed, and the results inserted into the HTML stream returned to the browser.

The concatenation operator (.) is used to join string values (including a blank space) together:

<?php
$first_name = "Dave";
$last_name = "Mercer";
$whole_name = $first_name . " " . $last_name;
echo "First name plus last name = <b>$whole_name</b>";
?>
The strlen () function finds and returns the length of a string. In this program, it returns a number indicating the count of characters in the string value contained in the $whole_name variable.

The strstr () function finds and returns any part of a string that is after the first instance of a particular character or string within a string. In this program, it searches the $whole_name variable value ("Dave Mercer") until it finds the first occurrence of the space character, and then returns everything after the first space.

The strpos () function finds and returns a number indicating the position within a string or a search string. In this case, searching for the string a within the $whole_name value, returns the position value 1. (Remember that the values start with 0, so the second position is 1.)
The chr () function returns a string character value corresponding to the decimal ASCII value entered as the argument. In this program, the string character for ASCII value 97 is returned.

Arithmetic Operators in PHP

In PHP, the arithmetic operators (plus, minus, and so on) work much as you would expect, enabling you to write expressions as though they were simple equations. For example, $c = $a + $b adds $a and $b and assigns the result to $c. (The = operator is entirely different than the comparison operators = = and = = =, which are discussed in Chapter 4.)

And just like ordinary equations, operator precedence makes a difference, and you can affect this precedence using parentheses. Here's an example;

<?php
$first_number = 20;
$second_number = 30;
$third_number = 3 ;
$fourth_number = 2;
$total = $first_number * $second_number / $third_number + $fourth_number;
$total2 = $first_number * $second_number / ($third_number + $fourth_number);
echo "Twenty times thirty divided by three plus two is <b>$total</b><br>";
echo "Twenty times thirty divided by (three plus two) is <b>$total2</b>";
?>
The difference made by the parentheses is clear when you run the program because the first echo statement returns a value of 202, whereas the second echo statement returns a value of 120.
Special Assignment Operators
The equals sign can be combined with other operators to give you a special assignment operator that makes it easier to write certain expressions. The special assignment operators (such as +=, -=, and so on) simply give you a shorthand method for performing typical arithmetic operations, so that you don't have to write out the variable name multiple times.

For example, you can write

$first_number +=  $second_number;
rather than

$first_number = $first_number  +  $second_number;
This also works for other kinds of operators. For example, the concatenation operator can be combined with the equals sign (as . =) so that the current value on the left side is concatenated to the value being assigned on the right, like this:

$a = "Start a sentence ";
$b = "and finish it.";
$a .= $b //gives Start a sentence and finish it.
The main arithmetic, string, and bitwise operators support combination in this fashion; check the PHP Web site for more information about which operators can be combined like this.
Using the Increment/Decrement Operators
There are often times when it's useful to add or subtract from a number the same amount over and over. This situation occurs so frequently that there are special operators to perform this task: the increment and decrement operators. They are written as two plus signs or two minus signs respectively, preceding or following a variable name, like so:

$a = ++$a; //adds one to $a and then returns the result
$a = $a++; //returns $a and then adds one to it
$b = --$b; //subtracts one from $b and then returns the result
$b = $b--; //returns $b and then subtracts one from it
The location of the operators does make a difference. Placing the operators before the variable name causes the effect (adding or subtracting one) to happen before the value of the variable is returned; placing the operators after the variable name returns the current value of the variable before causing the effect.
Interestingly, you can use the increment and decrement operators in a limited way with characters as well. For example, you can "add"one to the character B and the returned value is C. However, you cannot subtract from (decrement) character values.
Using PHP Math Functions
PHP incorporates many common mathematical functions, including some that require arguments, some that don't require arguments, and some in which arguments are optional. For example, you can use the floor () function to round a number down, no matter what the fractional amount is. But you must provide an argument to the function, otherwise, what would be the point? The argument is the initial value to find the floor for. For example, the find the floor value of 100.01, you'd use a line of code like this:

$a = 100.01;
$floor_a = floor($a);
On the other hand, functions like pi () and rand () require no arguments. The pi () function returns the value of pi to 14 decimal places (the default is 14, but your actual precision depends on your setting of the precision directive in your php. ini file). The rand function generates a (pseudo) random number from 1 to RAND_MAX (the maximum number, that varies by operating system), unless you supply it with arguments limiting the range of numbers from which the function can choose.

Try it, Out: Work With Numbers
Start example
Here's a little program that demonstrates working with numbers. You'll do some familiar operations, and a few that might not be so familiar, using some of the operators available with PHP, and some of the built-in functions. Once again, you embed your PHP code in HTML so that a Web page can display the results.
  1. Open your HTML editor and enter the following code. (Although it's good practice for you to enter all of this code, you may instead choose to download the file—working_with_numbers. php—from this book's Web site.)

    <html>
    <head>
    <title>Beginning PHP5</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    
    <body bgcolor="#FFFFFF">
    <table width="100%" border="1">
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif"><b>Working With
          Numbers</b></font></td>
        <td width="43%">&nbsp;</td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Using
          the Addition Operator   ( + ) </font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $first_number = 20;
    $second_number = 30;
    $total  = $first_number + $second_number;
    echo "Twenty plus thirty is <b>$total</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Using
          the  Increment  Operator (++) </font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $first_number = 20;
    $first_number = ++$ first_number;
    echo "Twenty incremented by one is <b>$first_number</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Using
          the Multiplication and Division Operators (*  and /)</font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $first_number = 20;
    $second_number =  30;
    $third_number = 3;
    $fourth_number = 2;
    $total = $first_number * $second_number  / $third_number + $fourth_number;
    $total2 = $first_number * $second_number / ($third_number + $fourth_number);
    echo "Twenty times thirty divided by three plus two is <b>$total</b><br>";
    echo "Twenty times thirty divided by (three plus two) is <b>$total2</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Special
          Assignment  Operators  -  Using  +=  and  *=</font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $first_number = 20;
    $second_number = 30;
    $total = $first_number += $second_number;
    $total2 = $first_number *= $second_number;
    echo "Twenty plus_equals thirty is <b>$total</b><br>";
    echo "Twenty time_equals thirty is <b>$total2</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-l">
    Getting
          the absolute value of a number - Using abs () </font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $frist_number = -2.7;
    echo "The absolute value of 2.7 is <b>" . abs($first_number) . "</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">
    Converting
          a binary number to a decimal number - Using bindec()</font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $binary..number = 10101111;
    $decimal_number = bindec ($binary_number) ;
    echo "The decimal equivalent of the binary number 10101111 is
    <b>$decimal_number</b>" ;
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Round
          Numbers up or down - Using ceil () and floor ()</font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    < ?php
    $first_number = 2.4;
    echo "2.4 rounded up is <b>" . ceil (first_number) . "</b> and rounded down is
    <b>"
    . floor ($first_number) . "</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-l">Finding
          the maximum or minimum value  -  Using max( )   and min( )</font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $max_value = max(2,3,4);
    $min_value = min(2,3,4);
    echo "The max value of  2,3,4 is <b>" , $max_value . "</b>, and the min value is
    <b>" . $min_value , "</b>";
    ?>
    /font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Get  the
          value  of  PI   -  Using pi ( ) </font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    echo "The value ot PI is <b>" . pi( ) . "</b>";
    ?>
    </font></td>
      </tr>
      <tr>
        <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-l">Get a
          random number - Using rand( ) </font></td>
        <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    echo "A random number is <b>" . rand() . "</b>";
    ?>
    /font></td>
     </tr>
     <tr>
       <td width="57%"><font face="Arial, Helvetica, sans-serif" size="-1">Get the
         square root - Using sqrt()</font></td>
       <td width="43%"><font face="Arial, Helvetica, sans-serif" size="-1">
    <?php
    $first_number = 20;
    echo "The square root of twenty is <b>" . sqrt($first_number)
    . "</b>";
    ?>
    </font></td>
      </tr>
    </table>
    </body>
    </html>
  2. Save the file as working_with_numbers.php, upload it if required, and then display it in your browser. 


End example

How it Works

You use the same format for displaying results in this program as you did with the last. This program demonstrates some simple calculations with operators, some basic use of built-in functions, and the results of several built-in functions that take no arguments (such as pi()).
In the code you set some values and then processed them with different sets of parentheses to illustrate how operator precedence works:

<?php
$first_number = 20;
$second_number = 30;
$third_number = 3;
$fourth_number = 2;
$total = $first_number * $second_number / $third_number + $fourth_number;
$total2 = $first_number * $second_number / ($third_number + $fourth_number);
echo "Twenty times thirty divided by three plus two is <b>$total</b><br>";
echo "Twenty times thirty divided by (three plus two) is <b>$total2</b>";
?>
Then increment and decrement operators were used to add or subtract one from the numerical value contained in the variables $a and $b.

$a = ++$a; //adds one to $a and then returns the result
$a = $a++; //returns $a and then adds one to it
$b = --$b; //subtracts one from $b and then returns the result
$b = $b--; //returns $b and then subtracts one from it
The use of the pi () and rand () functions demonstrates how to make PHP generate values for pi or that are random. Just write out the function with no arguments in between the parentheses, and that's all there is to it (other than using the equals sign to assign the value to a variable).

Arrays

Arrays are variables of type array (notice array is referred to as a data type), so you might be wondering why there's a whole section of this chapter for them. Yes, arrays are variables, but they are very special and powerful variables, and so deserve their own section.

Technically, arrays are lists made up of keys (the indexes) and values, which are the values contained in each element. Elements are the value containers in an array. You can think of an element as being similar to a separate variable, and being made up of a name/value pair.
Although some books imply that arrays can be very complex and hard to grasp, there's an easy way to think about them comfortably: Arrays are variables with many value containers, and several ways to access any particular value. They are almost like mini relational databases that are dynamic, in that they reside in memory only as long as the current program is executing (unless you store them in the session or in a real database between page requests). Array names are like the names of tables in a database, and an array container that contains another array is like a related table in a database. This analogy is not precise, but it can be very helpful when thinking about how to create or access arrays and their values.

Array Indexes

The array () function (actually, it is a language construct, not a function, but is written the same way as a function) is used to create an array, and accepts as arguments the values you want to place in the array. An element in an array can be accessed by its index number. An index number is like a little address by which you can access that particular variable spot within an array. Because all the variable spots in an array begin with the name of the array, each particular spot must have its own unique number. Index numbers for arrays begin with zero (0). For example, in the following line of code, the $my_array variable is set equal to an array that has four elements numbered 0, 1, 2, and 3:

$my_array = array ("cat", "dog", "horse", "goldfish");
The variable $my_array is set to the result of the array () function. If you ran the is_array () function on $my_var, the result would be true, indicating that, sure enough, $my_var is structured as an array.

To access the values in the array just created, you can use code such as the following:

$zero_element = $my_array[0];
$one_element = $my_array[1];
$two_element = $my_array[2];
$three_element = $my_array[3];

Using Strings as Array Indexes

Because you can use arrays in so many situations, it's often helpful to give elements a name rather than simply let them adopt the next number (starting with 0) in sequence. For example, the following code produces an array in which each element has a string as a name, and then sets a series of variables to the values of each named string:

$my_named_array = array("dog" => "rover", "cat" => "pinky", "hamster" =>
"fluffball");
$my_dog = $my_named_array["dog"];
$my_cat = $my_named_array["cat"];
$my_hamster = $my_named_array["hamster"];
echo "My dog is named $my_dog, my cat is named $my_cat,
 and my hamster is named $my_hamster";
The capability to access a value by name is important because you don't need to have any idea what the sequence of values or the actual index number is—you only need to know the name you gave to that element. When using strings as array indexes, it's best to use quotes around the array names. Although it's easy and convenient to leave the quotes off, the online documentation warns against this practice, anticipating the time when the quotes become mandatory and not using quotes will break your code.

If you wanted to, you could still use the index number instead of the names you've assigned, because PHP arrays always keep index numbers as well as any assigned names, so the following code would work exactly the same as the last example:

$my_named_array = array("dog" => "rover", "cat" => "pinky",
"hamster" => "fluffball");
$my_dog = $my_named_array[0];
$my_cat = $my_named_array[1];
$my_hamster = $my_named_array[2];
echo "My dog is named $my_dog, my cat is named $my_cat,
 and my hamster is named $my_hamster";

Initializing Arrays

You can initialize (create and set initial values for) arrays in a number of ways. For example, you can use the array () function, as you've already done or you can end a variable name with square brackets ([]). Writing a variable name and placing empty square brackets at the end causes PHP to decide that you intend to create an array, and to begin to increment the index from zero if it is the first element in the array, as shown here:

$my_array[] = "first element";
If you want to give the element a name, just put it inside the square brackets, like so:

$my_array["first"] = "another_first element";
If you used $my_array [" first" ] again, PHP would overwrite the value you just assigned instead of creating a new element. If you use $my_array [ ] again, PHP would assign an index number (the next one in sequence) and create a new element on your array.

An interesting thing about arrays: a single array can hold many different values, each of a different type as required by your program (the indexes for each element can be only strings or integers). This means you really can use an array to hold data much like a record in a database table holds data.

Working with Arrays

Sometimes after creating and initializing an array (especially with values from a record in a database table) it can be a bit difficult to know what those values might be, and therefore hard to debug your code. Fortunately, the print_r() function enables you to print out the entire list contained in an array, along with the names of each indexed element. To follow along with this example, create a simple HTML page and embed the following PHP code in it:

<?php
$my_named_array = array("dog" => "rover", "cat" => "pinky",
 "hamster" => "fluffball");
print_r($my_named_array) ;
?>
Run the file in your browser. 

Using print_r is very helpful if you want to look at all the contents of an array. In Chapter 4 you'll learn about specialized loops, which also provide very easy access to all the values in an array.

Arrays are real workhorses in PHP, as in many other languages, and PHP comes complete with many built-in functions specifically for working with arrays. You'll explore a couple of the most used functions here, and begin to work with them more in Chapters 3 and 4; you'll notice that many of them are similar to functions you can use on databases.

There are often times when you don't know how many elements are in an array, but you can use the count () function to count them (or the elements in any variable for that matter), like this:

$number_of_elements = count($my_array);

The array_count_values () function is not quite the same, because it returns (as an array) the frequency of occurrence of matching values in the array used as an argument to it. The element names in $returned_array are the values in $argument_array, and the values in $returned_array are the number of times the value occurred in the $argument_array. This may be this easier to understand by reading the following code:

$argument_array = array("dog", "dog" "cat", "cat", "hamster");
$returned_array = array_count_values($argument_array);
print_r($returned_array);
This prints out:

Array
(
    [dog] => 2
    [cat] => 2
    [hamster] => 1
)
The array_f1ip() function is useful when you need to swap values for key names and vice versa. For example, if you have a list of people's names as element names in an array, and the value of each is a SSN (Social Security number), you may want to flip the array so you can access each person by his SSN (because the SSN should be unique, although their names may be duplicated in some cases). You could accomplish this using the following code:

$my_people_array = array("John" => "555-66-7777", John => "444-55-3333");
$my_ssn_array = array_flip($my_people_array);
You could then use $my_ssn_array to look people up uniquely, even though John appears twice.

Sorting Arrays With sort() and asort()

It's often convenient to sort the elements in an array, such as when you want to produce a list of names in alphabetical order, and you can do just that with the sort () function. If you want to maintain the order of the indexes, use asort (). The sort function rebuilds the indexes into the proper order whereas changing the order of the element values, but asort () keeps the indexes stuck to their element values. The code can be written:

$my_unsorted_array = array("Jim", "Bob", "Mary");
$my_sorted_array = sort($my_unsorted_array);
$my_sorted_array_with_unchanged_indexes = asort($my_unsorted_array);