PHP Variables and Operators

Very simply put, variables represent data. If you want your script to hold onto a specific piece of information, first create a variable and then assign a literal value to it using the equal sign (=).

For example, the variable username holds the literal value "joe" when appearing in your script as

 $username = "joe"; 

Variable names begin with the dollar sign ($) and are followed by a concise, meaningful name. The variable name cannot begin with a numeric character, but it can contain numbers and the underscore character (_). Additionally, variable names are case sensitive, meaning that $YOURVAR and $yourvar are two different variables.

Creating meaningful variable names is another way to lessen headaches while coding. If your script deals with name and password values, don't create a variable called $n for the name and $p for the password-those are not meaningful names. If you pick up that script weeks later, you might think that $n is the variable for "number" rather than "name," and that $p stands for "page" rather than "password."

This section describes several kinds of variables. Some variables change values as your script runs, and others are assigned values outside of your PHP script-such as HTML forms.

Variables and Value Types

You will create two main types of variables in your PHP code: scalar varriables and arrays. Scalar variables contain only one value at a time, while arrays contain a list of values or another array (thus producing a multi-dimensional array). Within variables, their associated values can be of different types, such as the following:

  • Integers. Whole numbers (numbers without decimals). Examples are 1, 345, and 9922786. You can also use octal and hexadecimal notation: the octal 0123 is decimal 83 and the hexadecimal 0x12 is decimal 18.

  • Floating-point numbers ("floats" or "doubles"). Numbers with decimals. Examples are 1.5, 87.3446, and 0.88889992.

  • Strings. Text and/or numeric information, specified within double quotes (" ") or single quotes (' ').

As you begin your PHP script, plan your variables and variable names carefully, and use comments in your code to remind you of the assignments you've made.

Local and Global Variables

Variables can be local or global, the difference having to do with their definition and use by the programmer, as well as where they appear in the context of the scripts you're creating. The variables described in the previous section-and in the majority of this book-are local variables.

By default, PHP variables can be used only by the script they live within. Scripts cannot magically reach inside other scripts and use the variables created and defined within them-unless you purposely share them with other scripts. For example, when creating your own functions (blocks of reusable code that perform a particular task), you define the shared variables as global-that is, able to be accessed by other scripts and functions that need them.

You will learn more about creating your own functions, and about using global as well as local variables, later in this chapter. For now, just understand that there are two different variable scopes-local and global-that will come into play as you write more advanced scripts.

Pre-defined Variables

In all PHP scripts, a set of pre-defined variables is in use. You may have seen some of these variables in the output of the phpinfo() function if you scrolled down and read through the entire results page. Some of these pre-defined variable are also called superglobals, essentially meaning that they are always present and available in your scripts.

Study the following list of superglobals, as they will be used throughout this book. Each of these superglobals is actually an array of other variables. Don't worry about fully understanding this concept now, as it will be explained as you move along through the book.

  • $_GET. Any variables provided to a script through the GET method.

  • $_POST. Any variables provided to a script through the POST method.

  • $_COOKIE. Any variables provided to a script through a cookie.

  • $_FILES. Any variables provided to a script through file uploads.

  • $_ENV. Any variables provided to a script as part of the server environment.

  • $_SESSION. Any variables that are currently registered in a session.

Note 

If you are using a version of PHP earlier than 4.1.x and cannot upgrade to a newer version of PHP (as described in Chapter 1), you must adjust the names of these variables when following the scripts in this book. The old names are $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, $HTTP_POST_FILES, $HTTP_ENV_VARS, and $HTTP_SESSION_VARS.

Using Constants

A constant is an identifier for a value that cannot change during the course of a script. Once a constant has a value, that value remains throughout its execution lifetime. Constants can be user-defined, or you can use some of the predefined constants that PHP always has available. Unlike simple variables, constants do not have a dollar sign before their name, and they are usually uppercase, in order to distinguish them from scalar variables.

The function used to define a constant is called define(), and it requires the name of the constant and the value you want to give it. In the following code snippet, you define a constant called MYCONSTANT with a value of "This is a test of defining constants." Then the echo command will echo the value of the constant to the screen.

 <? define("MYCONSTANT", "This is a test of defining constants."); echo MYCONSTANT; ?> 

The output of this script is just

  • This is a test of defining constants.

There are some common pre-defined constants in PHP, including:

  • __FILE__. The name of the script file being parsed.

  • __LINE__. The number of the line in the script being parsed.

  • PHP_VERSION. The version of PHP in use.

  • PHP_OS. The operating system using PHP.

You can create a script to test them all out.

 <? echo "<br>This file is ".__FILE__; echo "<br>This is line number ".__LINE__; echo "<br>I am using ".PHP_VERSION; echo "<br>This test is being run on ".PHP_OS; ?> 

Save the file with the name constants.php and place it on your Web server. When you access this file, you should see the strings you typed, plus the values of the constants. For example:

 This file is /usr/local/bin/apache/htdocs/constants.php This is line number 4 I am using 4.3.0 This test is being run on Linux 

Operator Types

Values are assigned to variables using different types of operators. A list of common operators and operator types follows. For a complete list, see the "Operators" section in Appendix A, "Essential PHP Language Reference."

Assignment Operators

You've already seen an assignment operator at work: the equal sign (=) in $username = "joe"; is the basic assignment operator.

Note 

The single equal sign does not mean "equal to." Instead, the single equal sign always means "is assigned to." The double equal sign ("==") means "equal to." Commit this to memory to alleviate debugging headaches.

Other assignment operators include +=, -=, and .=.

 $ex += 1;    // Assigns the value of ($ex + 1) to $ex.                   // If $ex = 2, then the value of ($ex += 1) is 3. $ex -= 1;    // Assigns the value of ($ex - 1) to $ex.                   // If $ex = 2, then the value of ($ex -= 1) is 1. $ex .= "coffee";  // Concatenates (adds to) a string. If $ex = "I like " // then the value of ($ex .= "coffee") is "I like coffee". 

Arithmetic Operators

Even if you've never written a line of code in your life, you already know most of the arithmetic operators-they're basic math!

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus, or "remainder"

In the following examples, $a = 5 and $b = 4.

 $c - $a + $b;    // $c = 9 $c - $a - $b;    // $c = 1 $c - $a * $b;    // $c = 20 $c - $a / $b;    // $c = 1.25 $c - $a % $b;    // $c = 1 

You don't have to limit mathematical operations to variables-you can use hard-coded numbers as well. For example:

 $c = 3 + 4;      // $c = 7 $c = 8 * 4;      // $c = 32 $c = $a * 10;    // $c = 50 

Comparison Operators

It should come as no surprise that comparison operators compare two values. As with the arithmetic operators, you already know most of the comparison operators.

==

Equal to

!=

Not equal to

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

In the following examples, $a = 5 and $b = 4.

  • Is $a == $b? No; 5 does not equal 4. The comparison is FALSE.

  • Is $a != $b? Yes; 5 does not equal 4. The comparison is TRUE.

  • Is $a > $b? Yes; 5 is greater than 4. The comparison is TRUE.

  • Is $a < $b? No; 5 is not less than 4. The comparison is FALSE.

  • Is $a >= $b? Yes; although 5 does not equal 4, 5 is greater than 4. The comparison is TRUE.

  • Is $a <= $b? No; 5 does not equal 4, and 5 is not less than 4. The comparison is FALSE.

Comparison operators are often used in conjunction with control statements (if...else, while) to perform a specific task based on the validity of expressions. For example, if you are writing a number-guessing program and you want your script to print "That's the right number!" when a successful guess is made, you might include the following code:

 // secret number 5 if ($guess == "5") {              echo "That's the right number!"; } else {              echo "Sorry. Bad guess."; } 

Logical Operators

Logical operators, like comparison operators, are often found within if...else and while control statements. These operators allow your script to determine the status of conditions and, in the context of your if...else or while statements, execute certain code based on which conditions are true and which are false.

A common logical operator is ||, meaning OR. The following example shows the evaluation of two variables and the result of the statement. In this example, I really want to drink coffee. I have two options, $drink1 and $drink2. If either of my options is "coffee", I will be happy. Otherwise, I'll still need caffeine.

 $drink1 = "coffee"; $drink2 = "milk";              if (($drink1 == "coffee") | ($drink2 == "coffee")) {                   echo "I'm happy!";              } else {                   echo "I still need caffeine.";              } 

In this example, because the value of the $drink1 variable is "coffee", the logical OR comparison of $drink1 and $drink2 is TRUE, and the script returns "I'm happy!"

Other logical operators include AND (&&) and NOT (!).

Using Variables and Operators: A Calculation Script

You now have a fundamental knowledge of variables and operators-enough to create a PHP script that does some sort of variable calculation and displays results. To begin, open your favorite text editor, create a file called calc01.php, and set up the HTML "shell" around your script.

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Calculate Va1ues</TITLE> </HEAD> <BODY> <?php              // PHP code goes here. ?> </BODY> </HTML> 

Note 

In the following examples, replace the <?php ?> block with the code provided.

This script will use hard-coded values. In later sections, you'll learn how to use values from outside your PHP script in order to make this a working calculation form.

The calc01.php script will calculate an order for coffee beans. We know only the following information:

  • The price of one bag of beans is $10.00, including shipping.

  • Sales tax is 8.25 percent.

  • Joe wants four bags.

Begin the PHP portion of the script by creating variables for your known information and assigning values to those variables.

 $price = 10.00; $sales_tax = 8.25; $quantity = 4; 

You know that to find the subtotal of an order, you multiply the price of the item by the quantity ordered. You've just found another variable: $sub_total. Your list now looks like this:

 $price = 10.00; $sales_tax = 8.25; $quantity = 4; $sub_total  = $price * $quantity; 

You also know that the grand total of an order is the subtotal of the order plus the sales tax amount. The sales tax amount is determined by multiplying the sales tax by the subtotal of the order. You now know all of your remaining variables: $sales_tax_amount and $grand_total. The final list of PHP variables looks like this:

 $price = 10.00; $sales_tax = .0825; $quantity = 4; $sub_total = $price * $quantity; $sales_tax_amount = $sub_total * $sales_tax; $grand_total = $sub_total + $sales_tax_amount; 

Now that you have all the numbers, you'll want to display the results in the browser. You display the value of a variable with the echo command, just as if you were displaying a normal text string. The following chunk of code should go between the PHP start and end tags in your original shell:

 $price = 10.00; $sales_tax = .0825; $quantity = 4; $sub_total =- $price * $quantity; $sales_tax_amount = $sub_total * $sales_tax; $grand_total = $sub_total + $sales_tax_amount; echo "<P>You ordered $quantity bags of coffee.</p>"; echo "<P>Bags of coffee are $price each.</p>"; echo "<P>Your subtotal is $sub_total.</p>"; echo "<P>Sales tax is $sales_tax in this location.</p>"; echo "<P>$sales_tax_amount has been added to your order.</p>"; echo "<P>You owe $grand_total for your coffee.</p>"; 

Save the whole file and place it on your Web server. Now access it with your browser at its URL, http://127.0.0.1/calc01.php.

In your browser window, you should see this:

  • You ordered 4 bags of coffee.

  • Bags of coffee are 10 each.

  • Your subtotal is 40.

  • Sales tax is 0.0825 in this location.

  • $3.3 has been added to your order.

  • You owe 43.3 for your coffee.

While these calculations are correct, the results could use a little formatting help-you could place a dollar sign before the amount, display the sales tax as a percentage, and show the amount with two decimal places.

To print a dollar sign, place a backslash (\) before it. Dollar signs must be escaped, or delineated, in this way because dollar signs are also used to indicate the presence of a variable. In your script, use

 echo "<P>Bags of coffee are \$$price each.</p>"; 

to print a dollar sign before the value of $price. The result will look like this:

  • Bags of coffee are $10 each.

Add the escaped dollar sign to other echo statements containing dollar amounts.

To get the percentage value of $sales_tax, first create a new variable called $sales_tax_pct. Then transform the value 0.0825 into 8.25 by multiplying 0.0825 by 100.

 $sales_tax_pct = $sales_tax * 100; 

The variable $sales_tax_pct now contains the value 8.25. Rewrite the echo statement to include the new variable and the percent sign.

 echo "<P>Sales tax is $sales_tax_pct% in this location.</p>"; 

Here's the result:

  • Sales tax is 8.25% in this location.

The final bit of formatting, which ensures that the dollar amount prints to two decimal places, involves the use of the sprintf() function. This function takes two arguments: the formatting argument and the name of the value to be formatted. The following code takes the value of $price, formats it by creating a floating-point number with two decimal places, and puts the value (10.00) into a new variable called $fmt_price:

 $fmt_price = sprintf("%0.2f",$price); 

Repeat this process for the other monetary values in the script: $sub_total and $grand_total.

 $fmt_price = sprintf("%0.2f",$price); $fmt_sub_total = sprintf("%0.2f",$sub_total); $fmt_sales_tax_amount = sprintf("%0.2f",$sales_tax_amount); $fmt_grand_total = sprintf("%0.2f",$grand_total); 

In your echo statements, replace the old variables with the newly formatted variables. The PHP portion of your script should now look something like this:

 <?php          $price = 10.00;          $sales_tax = .0825;          $quantity = 4;          $sub_total = $price * $quantity;          $sales_tax_amount = $sub_total * $sales_tax;          $sales_tax_pct = $sales_tax * 100;          $grand_total = $sub_total + $sales_tax_amount;          $fmt_price = sprintf("%0.2f", $price);          $fmt_sub_total = sprintf("%0.2f",$sub_total);          $fmt_sales_tax_amount = sprintf("%0.2f", $sales_tax_amount);          $fmt_grand_total = sprintf("%0.2f", $grand_total);          echo "<P>You ordered $quantity bags of coffee.</p>";          echo "<P>Bags of coffee are \$$fmt_price each.</p>";          echo "<P>Your subtotal is \$$fmt_sub_total.</p>";          echo "<P>Sales tax is $sales_tax_pct% in this location.</p>";          echo "<P>\$$fmt_sales_tax_amount has been added to your order.</p>";          echo "<P>You owe \$$fmt_grand_total for your coffee.</p>"; ?> 

Name this version of the script calc02.php, place it on your Web server, and access it with your browser at its URL, http://127.0.0.1/calc02.php. In your browser window, you should now see this:

  • You ordered 4 bags of coffee.

  • Bags of coffee are $10.00 each.

  • Your subtotal is $40.00.

  • Sales tax is 8.25% in this location.

  • $3.30 has been added to your order.

  • You owe $43.30 for your coffee.

You've just completed your first script using variables and operators. In the next section, you'll learn the basics of working with arrays.

Working with Arrays

In brief, an array in PHP is a structure that acts as a map of keys and values. Single-dimensional arrays, wherein you have a single set of keys that maps to a single set of values, are the most commonly used arrays. For example, suppose you wanted to store your favorite colors in an array, for use later in a script. If you have three favorite colors, say, blue, black, and red, then you know you're going to have a set of three keys and values.

In the following example, $fave_colors is an array that contains strings representing array elements. In this case, the array elements are names of colors. Array elements are counted with 0 as the first position in the numerical index.

 $fave_colors[0] = "blue"; $fave_colors[1] = "black"; $fave_colors[2] = "red"; 

To create a single-dimensional array, you use the array() function.

For example, to create an array called $fave_colors, which holds the values "blue", "black", and "red" in positions 0, 1, and 2, use the following:

 $fave_colors = array("blue", "black", "red"); 

If you wanted to explicitly define the keys used in your array-for example, if you wanted to use strings, then you would use:

 $fave_colors = array("1st" => "blue", "2nd" => "black", "3rd" => "red"); 

The keys in this array would be "1st", "2nd" and "3rd", mapping to elements "blue", "black", and "red". Arrays are very useful for storing elements in lists and tables for later use.

Multidimensional Arrays

A multidimensional array is just what it sounds like-an array with more than one dimension, or a bunch of arrays within an array. Say, for example, you wanted to create an array just called $favorites, which would hold your favorite colors, numbers, and foods. You still use the array() function, just several times over.

 $favorites = array("colors" => array("blue", "black", "red"),                           "numbers" => array(3, 5, 21),                           "foods" => array("pizza", "sushi", "prime rib")                   ); 

The keys in the $favorites array would be "colors", "numbers", and "foods", mapping to the second level of arrays. Those arrays each use their own index, starting with position 0. So, to get the value of "sushi", you would use $favorites["foods"][1].

In the next section, you'll learn how to easily get values out of arrays.

Traversing Arrays

Once you have elements in an array, you'll obviously want to retrieve them! The most efficient method for retrieving keys and values from a single-dimensional array is to use the foreach construct. Here's how it works-given an array, the foreach function will read the key name and value of the current element, and then advance its internal pointer by one step. Then it will keep going on to the next element.

Check out the following array:

 $fave_colors = array("1st" => "blue", "2nd" => "black", "3rd" => "red"); 

Use this snippet to produce a list of elements in the array.

 <?php $fave_colors = array("1st" => "blue", "2nd" => "black", "3rd" => "red"); foreach ($fave_colors as $key => $value) {     echo "Key: $key ... Value: $value<br>"; ) ?> 

The resulting output is:

  • Key: 1st... Value: blue

  • Key: 2nd ... Value: black

  • Key: 3rd ... Value: red

There are plenty of PHP functions designed especially for working with arrays. See the "Array Functions" section of Appendix A, "Essential PHP Language Reference," or the Arrays section of the PHP Manual, at http://www.php.net/array.

User-Defined Functions

When you program in PHP, you will use predefined functions to achieve certain results. For example, the mail() function is a predefined function that sends mail. The mysql_connect() function is a predefined function that connects to a MySQL database. The code that makes up these functions is built into the PHP scripting engine, so you never see it. However, you can write your own functions and use them in your scripts, even storing your own functions in external files for use only when you need them.

Defining a Function

Functions have a very specific structure, wherein [function name] and [arguments] should be replaced with your own function name and any arguments you may want to use.

 function [function_name] ([arguments]) {              // code } 

When you create a function, you precede the name of the function with the literal word function. After the name of your function comes the list of arguments inside a set of parentheses. The arguments-which are optional, as you don't have to pass any arguments to a function if you don't want to-are separated by commas and hold values that your function needs in order to complete its task or tasks.

After the arguments, you open a set of curly braces, type in all of your code, and finally close the set of braces. For example, the following function (called multiplier) takes an argument called $num and multiplies the value by 5:

 function multiplier ($num) {              $answer = $num * 5; } 

Say you have already determined that $num equals 8, and that's what you're passing to the multiplier function. Using your math skills, you know that $answer will equal 40. To get that number back to your script, outside of the function, you must return the value.

Returning Values from Functions

The basic method for returning values from your functions is to use the return statement. Usually, this statement comes at the end of the function, like so:

 function multiplier ($num) {              $answer = $num * 5;              return $answer; } 

When you use a return statement, you can then call the function in your code, like so:

 echo multiplier(5); 

This usage would result in the following on your screen:

  • 40

As you are passing 8 as the $num argument to the multiplier() function, $answer becomes 40. As $answer is being returned as the result of the function's actions, and you're using echo followed by the function call, you're telling PHP to print the result of the code within the function. In this case, that result is the number 40.

Using a return statement to pass results from your functions to your main script is simple and safe, and it's one of the most common methods for doing so. If you do not use a return statement, then you must declare as global any variables you wish to pass back to your main script. For example:

 function multiplier($num) {              global $answer;              $answer = $num * 5; } 

In this case, you call the multiplier() function and then use the name of the variable in the echo statement, as it's not returned directly from your function. For example, using the modified function, the following code will print the number 40 to your screen:

 multiplier(5); echo $answer; 

If you had not declared $answer as a global variable, the result would have been a blank screen.

Using Functions in Your Code

So far, you've learned the basic structure of a user-defined function, but not how it fits within your own scripts. In the case of the multiplier() function, it does seem awfully time-consuming to create a script like the following just to print a number on the screen:

 <? function multiplier($num) {              $answer = $num * 5; return $answer; } echo multiplier(5); ?> 

Take a look at the function below, called db_connect(), which contains a database connection and selection code (don't worry about understanding this code right now; you'll learn more about database connections in the next chapter):

 function db_connect(): $connection = @mysql_connect("localhost", "username", "password")                   or die(mysql_error()); $db = @mysql_select_db($db_name, $connection)                   or die(mysql_error()); } 

Instead of typing all that information over and over in each script just to connect to a database server and select a database to use, imagine simply typing

 db_connect(); 

If your host name, username, password, or database name changes, you only have to change this information in one place-the db_connect() function code.

Retrieving Values from Forms

Now that you've learned a little bit about working with PHP, it's time to put together a static document and a PHP script and make them talk to each other. To be exact, you'll create an HTML form and a PHP script to retrieve values from that form.

As you'll recall, HTML forms always have three elements: a method, an action, and a submit button. When you click on a submit button in an HTML form, variables are sent to the script specified by the ACTION via the specified METHOD. The method can be either POST or GET. Variables passed from a form to a PHP script are placed in the global associative array (or superglobal) called $_POST or $_GET, depending on the form method. For example, the following HTML snippet calls a script called docalc.php using the POST method:

 <FORM method="POST" action="docalc.php"> <!--some form elements go here --> <INPUT type="submit" value="Calculate"> </FORM> 

The following form has one input text field and therefore passes one variable to a script called goform.php:

 <FORM method="POST" action="goform.php"> <P>Name: <INPUT type="text" name="your_name" size=10></P> <INPUT type="submit" value="Submit"> </FORM> 

Upon submission, the script goform.php receives a variable called $_POST[your_name], with a value of whatever the user typed in the form field. Variables are named according to the name attribute of the input field.

Putting a Form to Work

In this section, you'll use your knowledge of HTML forms and basic PHP scripting to develop an interactive version of the coffee bean calculator from earlier in this chapter. Before you create the form, recall some hard-coded variables from the calc01.php script earlier in this chapter: $price and $quantity. To make the script interactive, just create a form that allows the user to specify the values of these variables, and rewrite a little bit of the PHP to accommodate the usage of the $_POST superglobal.

To begin, open your favorite text editor, create a file called show_calculate.html, and set up an HTML shell:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Bean Counter Form</TITLE> </HEAD> <BODY>              <!-- your HTML form will go here --> </BODY> </HTML> 

To create the form code, assume that your PHP script will be called do_calculate.php and that your form will use the POST method.

 <FORM method="POST" action="do_calculate.php"> 

Next, create two simple text fields to capture the values for price and quantity.

 <P>Enter the price per bag of coffee beans: $ <INPUT type="text" name="price" size=10 maxlength=10></P> 

Use the MAXLENGTH attribute to set a maximum number of characters entered in the text field, including spaces.

 <P>How many bags would you like? <INPUT type="text" name="quantity" size=10 maxlength=10></P> 

Finally, add a submit button.

 <INPUT type="submit" value="Submit"> 

Don't forget the closing </FORM> tag!

Your HTML source code should look something like this:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Bean Counter Form</TITLE> </HEAD> <BODY> <FORM method="POST" action="do_calculate.php"> <P>Enter the price per bag of coffee beans: <INPUT type="text" name="price" size=10 maxlength=10></P> <P>How many bags would you like? <INPUT type="text" name="quantity" size=10 maxlength=10></P> <INPUT type="submit" value="Submit"> </FORM> </BODY> </HTML> 

Place this file on your Web server, and access it with your browser at its URL, http://127.0.0.1/show_calculate.html. In your browser window, you should see a form like that in Figure 2.1.

click to expand
Figure 2.1: Bean Counter form

Now that you have a form all set to send two variables to a script, it's time to create the script. You'll be making a few modifications to the calc01.php script, so rename it do_calculate.php and open it in your favorite text editor.

Make the following modifications:

  1. Change the title of the document to Bean Counter Results.

  2. Delete the initial value assignment statements for $price and $quantity.

  3. Replace all instances of $price and $quantity with $_POST[price] and $_POST[quantity], as these values will be coming from form input.

Your do_calculate.php script should look like this:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Bean Counter Results</TITLE> </HEAD> <BODY> <?php $sales_tax = .0825; $sub_total = $_POST[price] * $_POST[quantity]; $sales_tax_amount = $sub_total * $sales_tax; $sales_tax_pct = $sales_tax * 100; $grand_total = $sub_total + $sales_tax_amount; $fmt_price = sprintf("%0.2f",$_POST[price]); $fmt_sub_total = sprintf("%0.2f", $sub_total); $fmt_sales_tax_amount = sprintf("%0.2f", $sales_tax_amount); $fmt_grand_total = sprintf("%0.2f",$grand_total); echo "<P>You ordered $_POST[quantity] bags of coffee.</p>"; echo "<P>Bags of coffee are \$$fmt_price each.</p>"; echo "<P>Your subtotal is \$$fmt_sub_total.</p>"; echo "<P>Sales tax is $sales_tax_pct% in this location.</p>"; echo "<P>\$$fmt_sales_tax_amount has been added to your order.</p>"; echo "<P>You owe \$$fmt_grand_total for your coffee.</p>"; ?> </BODY> </HTML> 

Place this file on your Web server and open the Bean Counter form in your browser. Enter 10.00 in the first field and 4 in the second field, and then click the Submit button. You should see the same results as in the calc01.php script:

  • You ordered 4 bags of coffee.

  • Bags of coffee are $10.00 each.

  • Your subtotal is $40.00.

  • Sales tax is 8.25% in this location.

  • $3.30 has been added to your order.

  • You owe $43.30 for your coffee.

Try entering different values to see how the calculations turn out. Buying one bag of coffee at $14.25 should produce a grand total of $15.43, for example.

You can take the Bean Counter Form a step further by adding drop-down lists to your form and using conditional statements within your script to assign values to the variables sent from the form.

In your form, create a drop-down list of coffee types, replacing the question regarding the price of beans. Your form will pass the type of beans in a variable called $_POST[[beans].

 <P>Select a bean type:</P> <SELECT name="beans" size="1">              <OPTION value="Ethiopian Harrar">Ethiopian Harrar - $14.25</OPTION>              <OPTION value="Kona">Kona - $16.25</OPTION>              <OPTION value="Sumatra">Sumatra - $13.00</OPTION> </SELECT> 

Next, create a drop-down list of quantities, replacing the question about bags of coffee:

 <P>How many bags would you like?</P> <SELECT name="quantity" size="1">              <OPTION value="1">1</OPTION>              <OPTION value="2">2</OPTION>              <OPTION value="3">3</OPTION>              <OPTION value="4">4</OPTION>              <OPTION value="5">5</OPTION> </SELECT> 

Place this file on your Web server and access it with your browser at its URL, http://127.0.0.1/show_calculate.html. In your browser window, you should see the form shown in Figure 2.2.

click to expand
Figure 2.2: Modified Bean Counter Form

Now you will make a few more modifications to the do_calculate.php script, including setting up the pricing assignments for the variable $_POST[beans]. Open the script in your favorite text editor and add the following at the beginning of your PHP block:

 // set up the pricing assignments if ($_POST[beans] == "Ethiopian Harrar") {              $price = 14.25; } else if ($_POST[beans] == "Kona") {              $price = 16.25; } else if ($_POST[beans] == "Sumatra") {              $price = 13.00; } 

Previously, the user entered a number in a text field associated with the variable $_POST[price]. In the new version, the user selects a bean type and the script assigns a value to the variable $price, based on the value of $_POST[beans]. Replace all of the instances of $_POST[price] with $price, as that value is no longer coming from user input.

Using comparison operators, the script first checks to see if the value of $_POST[beans] is equal to the string "Ethiopian Harrar". If it is not, the script jumps to the next statement, to see if the value of $_POST[beans] is "Kona". If it still hasn't found a match, the script tries the last statement, to see if the value of $_POST[beans] is "Sumatra". As you are offering only three choices to the user, and the default value of the drop-down list is "Ethiopian Harrar", if you use the form interface you're assured of a match somewhere along the line.

Make two more modifications to the PHP script in order to return the selected bean type to the user instead of the generic term "coffee".

 echo "<P>You ordered $_POST[quantity] bags of $_POST[beans].</P>"; 

and

 echo "<P>Bags of $_POST[beans] are \$$fmt_price each.</P>"; 

The revised code for do_calculate.php should look something like this:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Bean Counter Results</TITLE> </HEAD> <BODY> <?php // set up the pricing assignments if ($_POST[beans] == "Ethiopian Harrar") {              $price = 14.25; } else if ($_POST[beans] == "Kona") {              $price = 16.25; } else if ($_POST[beans] == "Sumatra") {              $price = 13.00; } $sales_tax = .0825; $sub_total = $price * $_POST[quantity]; $sales_tax_amount = $sub_total * $sales_tax; $sales_tax_pct = $sales_tax * 100; $grand_total = $sub_total + $sales_tax_amount; $fmt_price = sprintf("%0.2f",$price); $fmt_sub_total = sprintf("%0.2f",$sub_total); $fmt_sales_tax_amount = sprintf("%0.2f",$sales_tax_amount); $fmt_grand_total = sprintf("%0.2f",$grand_total); echo "<P>You ordered $_POST[quantity] bags of $_POST[beans].</p>"; echo "<P>Bags of $_POST[beans] are \$$fmt_price each.</p>"; echo "<P>Your subtotal is \$$fmt_sub_total.</p>"; echo "<P>Sales tax is $sales_tax_pct% in this location.</p>"; echo "<P>\$$fmt_sales_tax_amount has been added to your order.</p>"; echo "<P>You owe \$$fmt_grand_total for your coffee.</p>"; ?> </BODY> </HTML> 

Save the file and place it on your Web server, and then open the Bean Counter form in your browser. Select Kona from the Bean Type drop-down list and 2 from the quantity drop-down list, and then click the Submit button. You should see the following results:

  • You ordered 2 bags of Kona.

  • Bags of Kona are $16.25 each.

  • Your subtotal is $32.50.

  • Sales tax is 8.25% in this location.

  • $2.68 has been added to your order.

  • You owe $35.18 for your coffee.

Try entering different values to see how the calculations turn out. Try buying five bags of Ethiopian Harrar, and see how expensive it is ($77.13)!

Displaying Dynamic Content

The Web is a dynamic environment, always changing and growing by leaps and bounds, so why not use your programming skills to display dynamic content? You can create a customized user environment by displaying specific content based on values sent through an HTML form, the type of browser being used, or (as you'll learn in later chapters) variables stored in cookies.

Redirecting to a New Location

Automatically redirecting a user to a new URL means that your script must send to the browser an HTTP header indicating a new location before it sends any other information. Many types of HTTP headers exist, from headers that indicate the character encoding and expiration date of the document to those that send the 404 - File Not Found error message. If you would like to learn more than anyone should ever know about headers, feel free to read the current HTTP 1.1 specification at http://www.w3.org/Protocols/rfc2068/rfc2068.

The format for sending an HTTP header from a PHP script is

 header(string) 

where string is the header text, in quotations.

Note 

This information bears repeating over and over again: Do not attempt to send information of any sort to the browser before sending a header(). You can perform any sort of database manipulations or other calculations before the header(), but you cannot print anything to the screen-not even a new line character.

The following code will print a redirection header to send the browser to the PHP site:

 <?php header("Location: http://www.php.net/"); exit; ?> 

Use the exit statement to ensure that the script does not continue to run.

Take the redirection script one step further, and add an HTML form with a drop-down list box as a front end to the redirection routine. Depending on the values sent by the form, the script redirects the browser to any of a number of URLs.

To begin, open your favorite text editor, create a file called show_menu.html, and set up an HTML shell. Next, create the form code with the assumption that your PHP script will be called do_redirect.php and your form will use the POST method.

 <FORM method="POST" action="do_redirect.php"> 

Now create a drop-down list box containing some menu options.

 <P>I want to go to: <SELECT name="location" size="l">         <OPTION value="http://www.premierpressbooks.com/">Premier Press</OPTION>         <OPTION value="http://www.php.net/">PHP.net</OPTION>         <OPTION value="http://www.thickbook.com/">thickbook.com</OPTION> </SELECT> 

Finally, add a submit button:

 <INPUT type="submit"  value="Go!"> 

Don't forget the closing </FORM> tag!

Your HTML source code should look something like this:

 <!DOCTYPE HTML PUBLIC  "-//W3C//OTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Redirection Menu</TITLE> </HEAD> <BODY> <FORM method="POST" action="do_redirect.php"> <P>I want to go to: <SELECT name="location" size="1">         <OPTION value="http://www.premierpressbooks.com/">Premier Press</OPTION>         <OPTION value="http://www.php.net/">PHP.net</OPTION>         <OPTION value="http://www.thickbook.com/">thickbook.com</OPTION> </SELECT> <INPUT type="submit" value"="Go!"> </FORM> </BODY> </HTML> 

Place this file on your Web server, and access it with your browser at its URL, http://127.0.0.1/show_menu.html. In your browser window, you should see the menu shown in Figure 2.3.

click to expand
Figure 2.3: Redirection Menu

Now, create the do_redirect.php script, which simply captures the value in $_POST[location] and sends the redirection header.

 <?php header("Location: $_POST[location]"); exit; ?> 

Save this file and place it on your server, and then access the menu at its URL, http://127.0.0.1/show_menu.html. Then, select a destination, click the Go! button, and away you (should) go!

Basic Environment Variable Usage

When a Web browser makes a request of a Web server, it sends along with the request a list of extra variables. These are called environment variables, and they can be very useful for displaying dynamic content or authorizing users.

The phpinfo() function also displays a wealth of information about the version of PHP that you are running and your Web server software, in addition to the basic HTTP environment. Create a file called phpinfo.php, containing only the following line:

 <?php phpinfo(); ?> 

To view a list of your environment variables and their values, place this file on your server and access it with your browser at its URL, http://127.0.0.1/phpinfo.php. For a list of general HTTP environment variables and their descriptions, visit http://hoohoo.ncsa.uiuc.edu/cgi/env.html.

Environment variables are part of the $_SERVER superglobal, and are referenced as $_SERVER[VAR_NAME]. For example, the REMOTE_ADDR environment variable is referenced as $_SERVER[REMOTE_ADDR].

The REMOTE_ADDR environment variable contains the IP address of the machine making the request. Create a script called remote_address.php that contains the following code:

 <?php echo "Your IP address is $_SERVER[REMOTE_ADDR]."; ?> 

Save this file and place it on your server, and then access it with your browser at its URL, http://127.0.0.1/remote_address.php.

You should see

  • Your IP address is [some number] on your screen.

For example, I see

  • Your IP address is 209.244.209.209.

This IP address is the address currently assigned to my computer by my Internet Service Provider.

In Chapter 4, "User Authentication," you'll learn how to use the REMOTE_ADDR environment variable as a form of user authentication by limiting the display of your Web site content to users accessing it from a specific domain or range of IP addresses.

Displaying Browser-Specific Code

The Browser War will never be won-no single Web browser will ever have 100 percent of the market share, nor will the browser makers ever fully comply with approved standards. So, using the HTTP_USER_AGENT environment variable, you can discern the specific attributes of the browser accessing your page and display code specifically designed for that browser type and platform. However, as you can imagine, there are hundreds of slightly different values. It's time to learn basic pattern matching!

Using the preg_match() PHP function, you'll create a script that finds a specific block of text within the value of $_SERVER[HTTP_USER_AGENT]. The syntax of preg_match() is

 preg_match("/[what you want to find]/", "[where you're looking]"); 

So, to find "MSIE" somewhere in the $_SERVER[HTTP_USER_AGENT] value, use

 (preg_match("/MSIE/i", "$_SERVER[HTTP_USER_AGENT]"); 

The i following /MSIE/ tells the script to match any instances, in uppercase or lowercase. Now, to find "Mozilla" in the $_SERVER[HTTP_USER_AGENT] value, use

 (preg_match("/Mozilla/i", "$_SERVER[HTTP_USER_AGENT]"); 

Put all the pieces together within an if[...]else statement so that if the browser is MSIE, "Using MSIE" will be printed on the screen. Or, if the browser is Netscape, "Using Netscape" will be printed on the screen. Or, if the browser is neither of those types, the $_SERVER[HTTP_USER_AGENT] value for that browser will be printed. Your code should look something like this:

 <?php if (preg_match("/MSIE/i", "$_SERVER[HTTP_USER_AGENT]")) {              echo "Using MSIE."; } else if (preg_match("/Mozilla/i", "$_SERVER[HTTP_USER_AGENT]")) {              echo "Using Netscape."; } else {              echo "$_SERVER[HTTP_USER_AGENT]"; } ?> 

Save this file as browser_match.php and place it on your Web server, then access it at its URL, http://127.0.0.1/browser_match.php.

In your browser window, you should see

  • Using MSIE

or

  • Using Netscape

or the value of $_SERVER[HTTP_USER_AGENT] for the browser you're using.

This sort of script is handy when you're developing a Web site using style sheets and you have one set of styles for MSIE and another set of styles for Netscape. You can use this same construct to print the style sheet link within the context of your code.

For example, a link to the style sheet,

 <LINK REV="stylesheet" HREF="msie_style.css"> 

would appear in the area indicated by

 <!-- stylesheet code goes here --> 

in the following HTML example:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Your Page</TITLE> <!-- stylesheet code goes here --> </HEAD> <BODY> </BODY> </HTML> 

If you have three style sheets, msie_style.css for MSIE-specific styles, ns_style.css for Netscape-specific styles, and other_style.css for all other browsers, replace the style sheet comment with the following block of PHP:

 <?php if (preg_match("/MSIE/i", "$_SERVER[HTTP_USER_AGENT]")) {           echo "<LINK REV=\"stylesheet\" HREF=\"msie_style.css\">."; } else if (preg_match("/Mozilla/i", "$_SERVER[HTTP_USER_AGENT]")) {           echo "<LINK REV=\"stylesheet\" HREF=\"ns_style.css\">."; } else {           echo "<LINK REV=\"stylesheet\" HREF=\"other_style.css\">."; } ?> 

This section of PHP code will seamlessly print the correct style sheet link in your HTML document, thus allowing you to safely use all the browser-specific styles you can think up.

Sending E-Mail

I can't think of any successful Web site that doesn't have some sort of feedback form or other mechanism for contact with users. When you see how incredibly easy it is to send e-mail with PHP, you might scratch your head in amazement and wonder why the rest of the world doesn't do this. That's a perfectly normal reaction (I still feel that way).

The mail() function takes four arguments: the recipient, the subject, the message, and the mail headers. So, if you want to send an e-mail to <joe@yourcompany.com>, with a subject of "Check this out!" and a message of "PHP is the best!", your entire PHP mail script could look like this:

 <?php mail("joe@yourcompany.com", "Check this out!", "PHP is the best!", "From: \"You\" <\"you@yourcompany.com\">\n"); ?> 

The e-mail will arrive in Joe's mailbox like any other mail message.

  • Subject: Check this out!

  • Date: [date sent]

  • From: You <"><you@yourcompany.com>>

  • To: <joe@yourcompany.com>

  • PHP is the best!

Now that you know how to send a simple e-mail, you can create a feedback form in HTML. A basic feedback form can contain text fields for the sender's name and e-mail address, a set of radio buttons asking if the user liked the site, and a text area for any additional message.

To begin, open your favorite text editor, create a file called show_feedback.html, and set up an HTML shell:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Feedback Form</TITLE> </HEAD> <BODY>              <!-- your HTML form will go here --> </BODY> </HTML> 

To create the form code, assume that your PHP script will be called do_send-feedback.php and your form will use the POST method.

 <FORM method="POST" action="do_sendfeedback.php"> 

Next, create two text fields to capture the values for $_POST[sender_name] and $_POST[sender_email]:

 <P>Your Name: <br><INPUT type="text" name="sender_name" size=30></P> <P>Your E-Mail Address: <br><INPUT type="text" name="sender_email" size=30></P> 

Add the radio button group to gather the value of $_POST[like_site].

 <P>Did you like this site? <INPUT type="radio" name="like_site" value="Yes" checked> yes <INPUT type="radio" name="like_site" value="No"> no </p> 

Add a text area so that the user can enter any additional message (captured in the variable $_POST[message]).

 <P>Additional Message: <br> <textarea name="message" cols=30 rows=5></textarea> </P> 

Finally, add the Send This Form button.

 <INPUT type="submit" value="Send This Form"> 

Don't forget the closing </FORM> tag!

Your HTML source code should look something like this:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Feedback</TITLE> </HEAD> <BODY> <FORM method="POST" action="do_sendfeedback.php"> <P>Your Name: <INPUT type="text" name="sender_name" size=30></P> <P>Your E-Mail Address: <INPUT type="text" name="sender_email" size=30></P> <P>Did you like this site? <INPUT type="radio" name="like_site" value="Yes" checked> yes <INPUT type="radio" name="like_site" value="No"> no </P> <P>Additional Message: <br> <textarea name="message" cols=30 rows=5></textarea> </P> <INPUT type="submit" value="Send This Form"> </FORM> </BODY> </HTML> 

Place this file on your Web server, and access it with your browser at its URL, http://127.0.0.1/show_feedback.html. In your browser window, you should see the form shown in Figure 2.4.

click to expand
Figure 2.4: Feedback form

Next, create the do_sendfeedback.php script. This script will capture the form values $_POST[sender_name], $_POST[sender_email], $_POST[like_site], and $_POST[message].

You must build the e-mail by concatenating strings to form one big message string (concatenating is a fancy word for "smashing strings together"). Use the newline (\n) and tab (\t) characters to add spacing where appropriate. Start building the message string in a variable called $msg.

 $msg = "Sender's Full Name:\t$_POST[sender_name]\n"; 

In this line, you want the e-mail to display a field label before the variable $_POST[sender_name] so that you know what $_POST[sender_name] is. For all you know, $_POST[sender_name] could be "Dog's Name".

Repeat the process, setting up field labels and results for $_POST[sender_email], $_POST[like_site], and $_POST[message]. In these lines, however, use the concatenation operator (.=) instead of the assignment operator (=).

 $msg .= "Sender's E-Mail:\t$_POST[sender_email]\n"; $msg .= "Did You Like the Site?\t$_POST[like_site]\n"; $msg .= "Additional Message:\t$_POST[message]\n\n"; 

Your message string ($msg) now will look like the following to the mail() function:

 "Sender's Full Name:\t$_POST[sender_name]\nSender's E- Mail:\t$_POST[sender_email]\nDid You Like the Site?\t$_POST[like_site]\nAdditional Message:\t$_POST[message]\n\n"; 

The e-mail client will format this into a nice e-mail with line breaks and tabs between elements. Now, create a variable called $mailheaders to force particular values in the From and Reply-To headers of your e-mail.

 $mailheaders = "From: My Web Site <myemail@domain.com>\n"; $mailheaders  .= "Reply-To: $sender_email\n\n"; 

Create the mail function, replacing the fake e-mail address with your own:

 mail("fakeemail@domain.com", "Feedback Form", $msg, $mailheaders); 

After your mail is sent, you should return some sort of text message to the browser so that the person doesn't sit there wondering if the message was sent or not. If a user doesn't know if a message has been sent, chances are good that he or she will continue to click the Submit This Form button, thereby flooding your mailbox with the same feedback form.

Add a few echo statements. You can even include the user's name in your response, as you have access to the variable $_POST[sender_name]:

 echo "<H1 align=center>Thank You, $_POST[sender_name]</H1>"; echo "<P align=center>We appreciate your feedback.</P>"; 

Your entire PHP script should look something like this:

 <?php $msg = "Sender's Full Name:\t$_POST[sender_name]\n"; $msg .= "Sender's E-Mail:\t$_POST[sender_email]\n"; $msg .= "Did You Like the Site?\t$_POST[like_site]\n"; $msg .= "Additional Message:\t$_POST[message]\n\n"; $mailheaders = "From: My Web Site <myemail@domain.com>\n"; $mailheaders .= "Reply-To: $sender_email\n\n"; mail("fakeemail@domain.com", "Feedback Form", $msg, $mailheaders); echo "<H1 align=center>Thank You, $_POST[sender_name]</H1>"; echo "<P align=center>We appreciate your feedback.</P>"; ?> 

Return to your Web browser, open the feedback form at its URL, http://127.0.0.1/show_feedback.html, and enter your name, e-mail address, and a message. After I submitted the form, the resulting page properly displayed my name and provided a thank-you message, as shown in Figure 2.5.

click to expand
Figure 2.5: Feedback Form Results page

I checked my e-mail, and I had indeed received a properly formatted message, including the $_POST[sender_name], $_POST[sender_email], $_POST[like_site], and $_POST[message] values.

So what about form validation? While ensuring that all fields are completed is not terribly crucial in this simple e-mail example, it will be important down the road when you start creating order forms. A very easy way to deal with required fields using PHP is to check for the required value and simply redirect the user back to the form if one of those values doesn't exist.

In the do_sendfeedback.php script, add the following code before building the message string, in order to check for an e-mail address and a message:

 if (($_POST[sender_email] == "") || ($_POST[message] == "")) { header("Location: http://127.0.0.1/show_feedback.html"); exit; } 

This code simply states, "If the value of $_POST[sender_email] is blank or if the value of $_POST[message] is blank, redirect the user back to a blank form so they can start again."

That's all there is to sending e-mail. In fact, you've made it through several simple areas of PHP functionality in this chapter, all of which you'll be able to put to good use in later chapters. In the remaining section of this chapter you'll learn the basics of reading and writing data files from the file system, including how to place the contents of a file into an e-mail and send it to a particular e-mail address.

Working with Your Filesystem

In addition to sending an e-mail full of data, you can create simple PHP scripts to create, open, and write to files on your Web server using the fopen() function, among others.

Writing Data Files

The fopen() function takes two arguments, file name and mode, and returns a file pointer. A file pointer provides information about the file and is used as a reference. The file name is the full path to the file you want to create or open, and mode can be any of the following:

  • r. Opens the existing file in order to read data from it. The file pointer is placed at the beginning of the file, before any data.

  • r+. Opens the existing file for reading or writing. The file pointer is placed at the beginning of the file, before any data.

  • w. Opens a file only for writing. If a file with that name does not exist, *w attempts to create a new file. If the file does exist, it deletes all existing contents and places the file pointer at the beginning of the file.

  • w+. Opens a file for reading and writing. If a file with that name does not exist, *w+ attempts to create a new file. If the file does exist, it deletes all existing contents and places the file pointer at the beginning of the file.

  • a. Opens a file only for writing. If a file with that name does not exist, *a attempts to create a new file. If the file does exist, it places the file pointer at the end of the file, after all other data.

  • a+. Opens a file for reading and writing. If a file with that name does not exist, *a+ attempts to create a new file. If the file does exist, it places the file pointer at the end of the file, after all other data.

So, to create a new file in your Web server document root (for example, /usr/local/apache/htdocs/) called mydata.txt, to be used to read and write data, use the following code:

 <?php $newfile = fopen("/usr/local/apache/htdocs/mydata.txt", "a+"); ?> 

In this example, $newfile is the file pointer. You can refer to this file pointer when reading, closing, or performing other functions with the file.

Note 

Remember to read to and write from tiles that are in an area accessible by your server process.

After you open a file, be sure to close it using the fclose() function:

 fclose($newfile); 

Opening a file just to close it again can get boring, so use the fwrite() or fputs() function to place data in the open file:

 fwrite([file], [data]); 

Note 

For all intents and purposes, fwrite() and fputs() are exactly the same.

Create a script called write_data.php, containing the following code:

 <?php $newfile = fopen("/usr/local/apache/htdocs/mydata.txt", "a+"); fwrite($newfile, "This is a new file."); fclose($newfile); echo "All done!"; ?> 

Be sure to modify the path to the file to match your own environment. Adding the echo statement after the file has been opened, written to, and closed will cause the message to be displayed after the actions have occurred. If any errors arise, such as problems with file permissions, you'll see those on the screen as well.

Note 

If your Web server runs on the Windows platform, escape the backslashes in your file path, like this:

 $newfile = fopen("c:\\Apache\\htdocs\\mydata.txt", "a+"); 

Place the PHP script on your Web server and access it with your browser at its URL, http://127.0.0.1/write_data.php. In your browser window, you should see the "All done!" message.

To verify that the message "This is a new file." has been written to mydata.txt, you can access it via URL if it has been placed above the document root, http://127.0.0.1/mydata.txt. If you placed the file in your home directory, such as /home/username/, navigate through your filesystem and open the file.

Reading Data Files

You can also use PHP to verify that a file has been written to by using the fread() function to gather the data into a variable. The fread() function takes two arguments:

 fread([filename], [length]); 

To read the complete file, length can be found using the filesize() function:

 fread([filename], filesize([filename])); 

To verify that the file mydata.txt, created in the preceding section, contains the string "This is a new file.", first create a script called read_data.php containing the following code:

 <?php // this variable contains the full path to the filename $file_loc = "/usr/local/apache/htdocs/mydata.txt"; // opens the file for reading only $whattoread = fopen($file_loc, "r"); // puts the contents of the entire file into a variable $file_contents = fread($whattoread, filesize($file_loc)); // close the file fclose($whattoread); echo "The file contains:<br>$file_contents"; ?> 

Be sure to modify the path to the file to match your own environment, then place the PHP script on your Web server and access it with your browser at its URL, http://127.0.0.1/read_data.php. In your browser window, you should now see the following:

  • The file contains:

  • This is a new file.

As well as reading the results on the screen, you can also send the contents in an e-mail. Add the following lines before the echo statement:

 $mailheaders = "From: My Web Site <myemail@domain.com> \n"; mail("youremail@domain.com", "File Contents", $file_contents, $mailheaders); 

And change the echo statement to:

 echo "Check your mail!"; 

The complete script should now look something like this:

 <?php // this variable contains the full path to the filename $file_loc = "/usr/local/apache/htdocs/mydata.txt"; // opens the file for reading only $whattoread = fopen($file_loc, "r"); // puts the contents of the entire file into a variable $file_contents = fread($whattoread, filesize($file_loc)); // close the file fclose($whattoread); //send the mail $mailheaders = "From: My Web Site <myemail@domain.com> \n"; mail("youremail@domain.com", "File Contents", $file_contents, $mailheaders); echo "Check your mail!"; ?> 

Place the PHP script on your Web server and access it with your browser at its URL, http://127.0.0.1/read_data.php. In your browser window, you should now see the message telling you to check your mail. When you do, a message should be waiting for you, containing file contents.

Later, you'll learn how to save form data on the filesystem and e-mail it to yourself on demand. But for now, pat yourself on the back for making it through all of these small examples of basic PHP functionality. You'll see, in later chapters, how actual applications are really based upon these basic types of functionality.



PHP Essentials
PHP Essentials, 2nd Edition
ISBN: 1931841349
EAN: 2147483647
Year: 2002
Pages: 74

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net