Wrox Home  
Search
Beginning PHP5, Apache, and MySQL Web Development
by Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K. Glass
February 2005, Paperback
US $39.99 Add To Cart


Excerpt from Beginning PHP5, Apache, and MySQL Web Development

Using Constants and Variables to Add Functionality

Using the echo function to display text the way you want it works no differently from coding an HTML page. However, using constants and variables allows you to take advantage of the power of PHP.

Overview of Constants

A constant is a placeholder for a value that you reference within your code. Constants are typically named with capital letters (so you can easily find them within your code), and the values are usually formally defined before using them. Constant names must begin with a letter or an underscore and cannot begin with a number. Names are also case-sensitive.

You define a value assigned to a constant with the PHP function define(). Once you've defined a constant, it can't be changed or undefined.

Try It Out — Using Constants

In this exercise, you'll see how you can use constants in your program.

1. Open your text editor and type the following program:
<html>
<head>
<title>My Movie Site</title>
</head>
<body>
<?php
  define ("FAVMOVIE", "The Life of Brian");
  echo "My favorite movie is ";
  echo FAVMOVIE;
?>
</body>
</html>
2. Save this file as moviesite.php and open it in your browser. You should see the text shown in Figure 1.
Figure 1
Figure 1

How It Works

By defining the constant known as FAVMOVIE, you have set the value as "The Life of Brian," which can be recalled and displayed later on. Although this constant can't be changed or reset throughout your script, it is available for use by any part of your script.

Overview of Variables

Unlike constants, variables are obviously meant to be variable — they are meant to change or be changed at some point in your program. Variables also do not need to be defined or declared and can simply be assigned when needed. Variables can hold either numeric or text values.

Variables are denoted with a dollar sign ($) and are case-sensitive, as are constants (in other words, $dateEntered and $DateEntered are not the same thing). The first letter of the variable name must be an underscore or letter and cannot be a number.

Previously, in PHP4, by default, variables were not passed by reference unless you prefaced them with an ampersand to force use of that practice. Beginning with PHP5, all variables will be passed by reference with no additional syntax required. This significantly increases the speed and power of your PHP programs. Don't worry if you don't understand what that means; it becomes more important in more advanced applications.

Try It Out — Using Variables

In this exercise, you'll add variables to your existing script.

1. Open your text editor and make the following changes to your moviesite.php file (noted in highlighted lines):
<html>
<head>
<title>My Movie Site</title>
</head>
<body>
<?php
  define("FAVMOVIE", "The Life of Brian");
  echo "My favorite movie is ";
  echo FAVMOVIE;
  
  echo "<br>";
  $movierate = 5;
  echo "My movie rating for this movie is: ";
  echo $movierate;
?>
</body>
</html>
2. Save the changes and access the file in your browser. Your screen should now look like the one in Figure 2.
Figure 2
Figure 2

How It Works

The value "5" is assigned to the variable movierate, and it is assigned as an integer value (number) instead of a string (text). The following line of code would cause the value of "5" to be seen as a string:

$movierate = "5";

By keeping this value as an integer, you can then perform mathematical calculations on this number later on (such as giving the viewer the average movie rate), as in this example:

<?php
  $bobsmovierate = 5;
  $joesmovierate = 7;
  $grahamsmovierate = 2;
  $zabbysmovierate = 1;
  $avgmovierate = (($bobsmovierate + $joesmovierate + $grahamsmovierate
                  + $zabbysmovierate) / 4);
  echo "The average movie rating for this movie is: ";
  echo $avgmovierate;
?>

PHP also has numerous built-in mathematical functions that you can use on variables that contain numbers, such as the following:

  • rand([min],[max]): Generates a random integer.
  • ceil(number): Rounds a decimal up to the next highest integer.
  • floor(number): Rounds a decimal down to the next lowest integer.
  • number_format(number [,dec places] [,dec point] [,thousands]): Formats the number based on the chosen number of decimal places, and uses the designated decimal point and thousands separator, if applicable. By default, PHP uses a period for the decimal point and a comma for the thousands separator, so if that's acceptable for you, then you can leave off the optional parameters, as noted in brackets above. If you would like to take out the comma, for example, you would type the following code:
    $price = 12345.67;
    number_format($price); //returns 12,345.67
    number_format($price, 2, ".", ""); //returns 12345.67
    
  • max(argument1, argument2, . . . ): Returns the maximum value of the supplied arguments.
  • min(argument1, argument2, . . . ): Returns the minimum value of the supplied arguments.

Passing Variables between Pages

Suppose your site allows viewers to enter their name on the front page. You'd like to be able to greet the user by name on each page in your site, but to do so, you need some way to pass the value of the name variable from page to page. There are basically four ways to accomplish this task: pass the variables in the URL, through a session, via a cookie, or with an HTML form. The method you choose is based on the situation and what best fits your needs at the time.

A Word about register_globals

Before we begin discussing the four methods of parsing variables between pages, you need to understand a little concept called register_globals. This is a configuration setting in your php.ini file that, when turned off, prevents the variable value from being falsely inserted by an outside source. While previous versions of PHP set the default setting in php.ini to "on," ever since version 4.2, the default has been switched to "off." This was the cause of many a programmer's sleepless night, because you must refer to your variables differently if register_globals is turned off, or else find all your variables' values coming up empty.

Although many third-party Web hosts have turned on register_globals, for security reasons not everyone does; we decided to assume that register_globals is off for the purposes of the exercises in this book. Coding with the assumption that register_globals has been turned off is the safest way to code because your program will work regardless of the server's setting.

Instead of calling variable values by the standard $varname syntax, when register_globals is "off" and you need to pass variables across pages, you need to refer to them in a different way, but only in the receiving page. You will see this in action in the next "Try It Out" section, but the various ways to refer to variables depend on how they are being sent.

Syntax When to Use It
$_GET['varname'] When the method of passing the variable is the "GET" method in HTML forms
$_POST['varname'] When the method of passing the variable is the "POST" method in HTML forms
$_SESSION['varname'] When the variable has been assigned the value from a particular session
$_COOKIE['varname'] When the variable has been assigned a value from a cookie
$_REQUEST['varname'] When it doesn't matter ($_REQUEST includes variables passed from any of the above methods)
$_SERVER['varname'] When the variable has been assigned a value from the server
$_FILES['varname'] When the variable has been assigned a value from a file upload
$_ENV['varname'] When the variable has been assigned a value from the operating environment

If you do not retrieve the variables using this syntax, the variable value will appear to be empty in your program and can cause you much grief in debugging!

Passing Variables through a URL

The first method of passing variables between pages is through the page's URL. You've undoubtedly seen URLs such as this:

http://www.mydomain.com/news/articles/showart.php?id=12345

This is an example of passing variable values through the URL. It requests that the article with the ID number of "12345" be chosen for the showart.php program. The text after the URL is called the query string.

You can also combine variables in a URL by using an ampersand (&), as in this example:

http://www.mydomain.com/news/articles/showart.php?id=12345&lang=en

This asks to retrieve the file with an ID of "12345" and the language presumably equal to "en," for English.

There are a few disadvantages to passing variables through a URL:

  • Everyone can see the values of the variables, so passing sensitive information isn't really very secure using this method.
  • The user can change the variable value in the URL, leaving your site potentially open to showing something you'd rather not show.
  • A user might also pull up inaccurate or old information using a saved URL with older variables embedded in it.

Try It Out — Using URL Variables

In this exercise, you'll modify your program to show the URL variables in action.

1. Modify your moviesite.php file as follows (changes are highlighted):
<html>
<head>
<title>My Movie Site - <?php echo $favmovie; ?></title>
</head>
<body>
<?php
  //delete this line: define("FAVMOVIE", "The Life of Brian");
  echo "My favorite movie is ";
  echo $favmovie;
  echo "<br>";
  $movierate = 5;
  echo "My movie rating for this movie is: ";
  echo $movierate;
?>
</body>
</html>

2. Save your moviesite.php file and start a new document in your text editor.
3. Type the following code:
<html>
<head>
<title>Find my Favorite Movie!</title>
</head>
<body>
<?php
  echo "<a href='moviesite.php?favmovie=Stripes'>";
  echo "Click here to see information about my favorite movie!";
  echo "</a>";
?>
</body>
</html>
4. Save this file as movie1.php and open it in your browser. Your screen should look like the one in Figure 3.
Figure 3
Figure 3
5. Now click the link and see what you get (see Figure 4).
Figure 4
Figure 4

You see the value for $favmovie as "Stripes" in the URL, as shown in Figure 4, but notice there is nothing shown for the value in the body of your page, nor in the title as it's supposed to be. If you have E_ALL turned on in your php.ini file, you will see the "undefined variable" error message.

What went wrong? You guessed correctly if you said register_globals! This is a prime example of how not retrieving the variables in the correct way can leave your pages not working and leave you perplexed. Now modify the moviesite.php file to fix the mistake.

1. Edit the following lines in your script (changes are highlighted):
<html>
<head>
<title>My Movie Site - <?php echo $_REQUEST['favmovie']; ?></title>
</head>
<body>
<?php
  echo "My favorite movie is ";
  echo $_REQUEST['favmovie'];
  echo "<br>";
  $movierate = 5;
  echo "My movie rating for this movie is: ";
  echo $movierate;
?>
</body>
</html>
Figure 5
Figure 5

How It Works

Here are a few points to note about your program:

  • As you can see from the "Title" section of your program, PHP code can be inserted in a straight line in the midst of your HTML code. This is helpful when you just need to insert one tidbit of information grabbed from PHP.
  • You can also insert PHP information anywhere in your HTML program, including the title.
  • You saw first-hand the effects of not taking into account register_globals when accessing a variable from another page, but did you notice that when you referred to $movierate, you did not have to include the register_globals syntax? This is because the value of $movierate is kept within moviesite.php; you did not get the information from another page or source.
  • $_REQUEST was chosen for your variable syntax because it really didn't matter in this example where the value for $favmovie came from. You were not trying to validate anything or prevent an unauthorized user from entering this page of the site: You simply wanted to pass the value across.

Special Characters in URLs

Passing variables through a URL poses an interesting problem if there are spaces, ampersands, or other special characters in the value of your variable. Luckily, substitutes exist for special characters that maintain the integrity of the variables' values. There is a special function called urlencode() to use when passing these values through a URL. If you wanted to change your favorite movie from "Stripes" to "Life of Brian," you would use urlencode() to encode the value and insert the proper HTML special characters.

To try this out, perform these steps:

1. Make the following highlighted changes to your movie1.php file:
<html>
<head>
<title>Find my Favorite Movie!</title>
</head>
<body>
<?php
  //add this line:
  $myfavmovie = urlencode("Life of Brian");

//change this line:
  echo "<a href='moviesite.php?favmovie=$myfavmovie'>";
  echo "Click here to see information about my favorite movie!";
  echo "</a>";
?>
</body>
</html>
2. Save the file and open it again in your browser. Clicking the link now displays the page shown in Figure 6.
Figure 6
Figure 6