Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

4.2 Variables

4.2.1 Definition and Assignment

Variables are fundamental to all programming languages. They are data items that represent a memory storage location in the computer. Variables are containers that hold data such as numbers and strings. In PHP programs there are three types of variables:

  1. Predefined variables
  2. User-defined variables
  3. Form variables related to names in an HTML form

Variables have a name, a type, and a value.

$num = 5;              // name: "$num", value: 5, type: numeric
$friend = "Peter";     // name: "$friend", value: "Peter", type: string
$x = true;             // name: "$x", value: true, type: boolean

The values assigned to variables can change throughout the run of a program whereas constants, also called literals, remain fixed.

PHP variables can be assigned different types of data, including:

  • Numeric
  • String
  • Boolean
  • Objects
  • Arrays

Computer programming languages like C++ and Java require that you specify the type of data you are going to store in a variable when you declare it. For example, if you are going to assign an integer to a variable, you would have to say something like:

int n = 5;

and if you were assigning a floating-point number:

float x = 44.5;

Languages that require that you specify a data type are called "strongly typed" languages. PHP, conversely, is a dynamically, or loosely typed, language, meaning that you do not have to specify the data type of a variable. In fact, doing so will produce an error. With PHP you would simply say:

$n = 5;
$x = 44.5;

and PHP will figure out what type of data is being stored in $n and $x.

4.2.2 Valid Names

Variable names consist of any number of letters (an underscore counts as a letter) and digits. The first letter must be a letter or an underscore (see Table 4.2). Variable names are case sensitive, so Name, name, and NAme are all different variable names.

Table 4.2. Valid and Invalid Variable Name Examples

Valid Variable Names

Invalid Variable Names

$name1

$10names

$price_tag

box.front

$_abc

$name#last

$Abc_22

A-23

$A23

$5

4.2.3 Declaring and Initializing Variables

Variables are normally declared before they are used. PHP variables can be declared in a script, come from an HTML form, from the query string attached to the script's URL, from cookies, from the server, or from the server's environment. Variable names are explicitly preceded by a $. You can assign a value to the variable (or initialize a variable) when you declare it, but it is not mandatory.

Format

$variable_name = value;    initialized
$variable_name;     uninitialized, value is null

To declare a variable called firstname, you could say:

$first_name="Ellie";

You can declare multiple variables on the same line by separating each declaration with a semicolon. For example, you could say:

$first_name; $middle_name; $last_name;

Double, Single, and Backquotes in Assignment Statements

When assigning a value to a variable, if the value is a string, then the string can be enclosed in either single or double quotes; if the value is returned from a function, then the function is not enclosed in quotes; and if the value is returned from a system command (see "Execution Operators" on page 143), then the command is enclosed in backquotes:

$name = "Marko";       // Assign a string
$city = 'San Francisco';   // Assign a string
$now = date("m/d/Y");  // Assign output of a function
$dirlist = 'ls -l';    // Assign output of a UNIX/Linux system command
$dirlist = 'dir /D/L'  // Assign a Windows system command

Example 4.8.

    <html>
    <head><title>Variables</title></head>
    <body bgcolor="lightblue">
    <font face = "arial" size='+1'>
    <?php
1       $name="Joe Shmoe";
2       $age=25.4;
3       $now=date("m/d/Y");
4       $nothing;
5       echo "$name is $age years old.<br />";
6       echo '$nothing contains the value of ', gettype($nothing),
              ".<br />";
7       echo "Today is $now<br />";
   ?>
   </font>
   </body>
   </html>

Explanation

1

The variable called $name is defined and initialized within the string value "Joe Shmoe". The string can be enclosed in either single or double quotes.

2

The variable called $age is assigned the floating-point value, 25.4. When assigning a number, the value is not quoted.

3

The variable called $now is assigned the return value of the built-in date() function. The function is not enclosed in quotes or it will not be executed. Its arguments, "m/d/Y", must be a string value, and are enclosed in quotes.

4

The variable $nothing is not assigned an initial value; it will have the value NULL.

5

The string is enclosed in double quotes. The floating-point value of $age is evaluated within the string.

6

The gettype() function tells us that the type of $nothing is NULL; that is, it has no value.

7

The output of the PHP built-in date() function was assigned to $now and is printed (see Figure 4.10).

04fig10.jpg

Figure 4.10 With or without quotes. Output from Example 4.8.

Example 4.9.

    <html><head><title>Backticks</title></head>
    <body bgcolor="lightgreen">
    <b>
    <pre>
    <?php
1       $month=`cal 7 2005`; // UNIX command
2       echo "$month<br />";
    ?>
    </b>
    </pre>
    </body>
    </html>

Explanation

1

The UNIX/Linux cal command and its arguments are enclosed in backquotes (also called backticks). In PHP the backquotes are actually operators (see "Execution Operators" on page 143). The command is executed by the operating system. Its output will be assigned to the variable, $month.

2

The PHP code is embedded within HTML <pre> tags to allow the calendar, $month, to be displayed in its natural format (see Figure 4.11).

04fig11.jpg

Figure 4.11 Backquotes and UNIX. Output from Example 4.9.

Example 4.10.

    <html><head><title>Backticks for Windows Command</title></head>
    <body bgcolor="66cccc">
    <b>
    <pre>
    <?php
1       $today =`date /T`; // Windows command
2       echo "Today is $today<br />";
    ?>
    </b>
    </pre>
    </body>
    </html>
04fig12.jpg

Figure 4.12 Backquotes and Windows. Output from Example 4.10.

4.2.4 Displaying Variables

The print and echo Constructs

So far, we have seen examples using both print and echo to display data. These language constructs can be used interchangeably. The only essential difference between echo() and print() is that echo allows multiple, comma-separated arguments, and print doesn't. Neither require parentheses around their arguments because technically they are not functions, but special built-in constructs. (In fact, arguments given to echo must not be enclosed within parentheses.) To print formatted strings, see printf and sprintf in Chapter 6, "Strings."

Consider the following. Three variables are declared:

$name = "Tom";
$state = "New York";
$salary = 80000;

echo() can take a comma-separated list of string arguments:

echo $name, $state, $salary;

print() takes one string argument:

print $name;

However, the concatenation operator can be used to print mutliple strings or strings containing multiple variables:

print $name . $state . $salary;
   echo $name . $state . $salary;

or all of the variables can be enclosed in double quotes:

print "$name $state $salary<br />";
   echo "$name $state $salary<br />";

If a variable is enclosed in double quotes, it will be evaluated and its value displayed. If enclosed in single quotes, variables will not be evaluated. With single quotes, what you see is what you get. Like all other characters enclosed within single quotes, the $ is treated as a literal character.

The following strings are enclosed in single quotes:

echo '$name lives in  $state and earns $salary.';
$name lives in $state and earns $salary.

print '$name lives in  $state and earns $salary.';
$name lives in  $state and earns $salary.

The same strings are enclosed in double quotes:

echo "$name lives in  $state and earns \$salary.";
Tom lives in New York and earns $80000.

print "$name lives in $state and earns \$salary.";
Tom lives in New York and earns $80000.

Shortcut Tags

There are several shortcuts you can use to embed PHP within the HTML portion of your file, but to use these shortcuts, you must make a change in the php.ini file. (If you don't know where to find the php.ini file you are using, look at the output of the built-in phpinfo() function where you will find the correct path to the file.) Use caution: The PHP developers set this directive to "off" for security reasons.

From the php.ini file:

; Allow the <? tag. Otherwise, only <?php and <script> tags are recognized.
; NOTE: Using short tags should be avoided when developing applications or
; libraries that are meant for redistribution, or deployment on PHP
; servers which are not under your control, because short tags may not
; be supported on the target server. For portable, redistributable code,
; be sure not to use short tags.
short_open_tag = Off                     <--Turn this "On" to make short tags work
   

Instead of using the print() or echo() functions to ouput the value of variables, they can be nested within HTML code by using <?= and ?> shortcut tags where they will automatically be evaluated and printed. (Note: There can be no space between the question mark and the equal sign.) All of the following formats are acceptable:

Format

<?= expression ?>
<?= $color ?>

<? echo statement; ?>
<? echo $color; ?>

You have chosen a <?= $color ?> paint for your canvas.

Example 4.11.

    <html>
    <head><title>Variables</title></head>
    <body bgcolor="lightblue">
    <?php
1       $name = "Marko";
2       $city = "San Francisco";
    ?>
    <font face = "verdana" size='+1'>
    <p>
3   Today is <?=date("l")?>. // same as <?php echo date("l"); ?>
    <br />
4   His name is <?=$name?> and he works in <?=$city?>.
    </font>
    </body>
    </html>

Explanation

1, 2

Two variables are assigned the string values, "Marko" and "San Francisco".

3, 4

The PHP shortcut tag is embedded within the HTML tags. PHP will evaluate the expression within the shortcut tags and print their values. The resulting HTML code contains the result of the evaluation as shown when viewing the browser's source (see Figure 4.13). In this example, the built-in date() function with a "l" option will return the day of the week. The variables, $name and $city are evaluated and placed within the HTML code.

04fig13.jpg

Figure 4.13 HTML source page viewed in the browser.

04fig14.jpg

Figure 4.14 Using shortcut tags. The output from Example 4.11.

4.2.5 Variables and Mixed Data Types

Remember, strongly typed languages like C++ and Java require that you specify the type of data you are going to store in a variable when you declare it, but PHP is loosely typed. It doesn't expect or allow you to specify the data type when declaring a variable. You can assign a string to a variable and later assign a numeric value. PHP doesn't care and at runtime, the PHP interpreter will convert the data to the correct type. In Example 4.12, consider the following variable, initialized to the floating-point value of 5.5. In each successive statement, PHP will convert the type to the proper data type (see Table 4.3).

Table 4.3. How PHP Converts Data Types

Variable Assignment

Conversion

$item = 5.5;

Assigned a float

$item = 44;

Converted to integer

$item = "Today was bummer";

Converted to string

$item = true;

Converted to boolean

$item = NULL;

Converted to the null value

Example 4.12 demonstrates data type conversion. The gettype built-in function is used to display the data types after PHP has converted the data to the correct type. See Figure 4.15 for the output.

Example 4.12.

    <html><head><title>Type Conversion</title></head>
    <body bgcolor="pink"><font size="+1">
    <?php
1   $item = 5.5;
        print "$item is a " . gettype($item) . "<br />";
2   $item = 44;
        print "$item is a " . gettype($item) . "<br />";
3   $item = "Today was a bummer!";
        print "\"$item\" is a " . gettype($item) . "<br />";
4   $item = true;
        print "$item is a " . gettype($item) . "<br />";
5   $item = NULL;
        print "$item is a " . gettype($item) . "<br />";
    ?>
    </body>
    </html>
04fig15.jpg

Figure 4.15 Mixing data types. Output from Example 4.12.

Type Casting

Like C and Java, PHP provides a method to force the conversion of one type of value to another using the cast operator (see Chapter 5, "Operators").

4.2.6 Concatenation and Variables

To concatenate variables and strings together on the same line, the dot (.) is used. The dot is an operator because it operates on the expression on either side of it (each called an operand). In expressions involving numeric and string values with the dot operator, PHP converts numeric values to strings. For example, consider the following statements:

// returns "The temperature is 87"
$temp = "The temperature is   " . 87;
// returns "25 days till Christmas"
$message =  25   .  " days till Christmas";

Example 4.13.

    <html>
    <head><title>Concatenation</title></head>
    <body bgcolor="ccff66">
    <b>
    <?php
1       $n = 5 . " cats";
2       $years = 9;
        print "The $n " . "lived ". $years * 5 .
3       " years. <br />";
4       echo "He owns ", $years. $n , ".<br />";
    ?>
    </b>
    </body>
    </html>

Explanation

1

Variable $n is assigned a number concatenated to a string. The number is converted to a string and the two strings are joined together as one string by using the concatenation operator, resulting in the string "5 cats".

2

Variable $years is assigned the number 9.

3

The concatenation operator joins all the expressions into one string to be displayed. The print() function can only take one argument.

4

The echo statement takes a list of comma-separated arguments, which causes the values of $years and $n to be displayed just as with the concatenation operator. See Figure 4.16 for the output.

04fig16.jpg

Figure 4.16 Concatenation.

4.2.7 References

Another way to assign a value to a variable is to create a reference (PHP 4). A reference is when one variable is an alias or pointer to another variable; that is, they point to the same underlying data. Changing one variable automatically changes the other. This might be useful in speeding things up when using large arrays and objects, but for now, we will not need to use references.

To assign by reference, prepend an ampersand (&) to the beginning of the old variable that will be assigned to the new variable; for example, $ref = & $old;. See Example 4.14 and it's output in Figure 4.17.

Example 4.14.

    <html><head><title>References</title></head>
    <body bgcolor="yellow"><font size="+1">
    <?php
1   $husband = "Honey"; // Assign the value "Honey" to $husband
2   $son = & $husband;  // Assign a reference to $son.
                        // Now $husband is a reference or alias
                        // for $husband. They reference the same data.
3   print "His wife calls him $husband, and his Mom calls him $son.
    <br />";
4   $son = "Lazy";     // Assign a new value to $son;
                       // $husband gets the same value
5    print "Now his wife and mother call him $son, $husband man.<br />";
     ?>
     <body>
     </html>
04fig17.jpg

Figure 4.17 References. Output from Example 4.14.

One important thing to note is that only named variables can be assigned by reference, as shown in Example 4.15.

Example 4.15.

<?php
$age = 26;
$old = &$age;      // This is a valid assignment.
$old = &(26 + 7);  // Invalid; references an unnamed expression.
?>

4.2.8 Variable Variables (Dynamic Variables)

A variable variable is also called a dynamic variable. It is a variable whose name is stored in another variable. By using two dollar signs, the variable variable can access the value of the original variable. Consider the following example:

$pet ="Bozo";
$clown = "pet";  // A variable is assigned the name of another variable
echo $clown;     // prints "pet"
echo ${$clown};  // prints Bozo

Dynamic variables are useful when you are dealing with variables that all contain a similar name such as form variables. Curly braces are used to ensure that the PHP parser will evaluate the dollar signs properly; that is, $clown will be evaluated first, and the first dollar sign removed, resulting in ${pet}, and finally $pet will be evaulated to "Bozo". Example 4.16 demonstrates how variable variables can be used dynamically to change the color of a font. Output is shown in Figure 4.18.

Example 4.16.

    <html>
    <head><title>Variable Variables</title></head>
    <body bgcolor="669966">
    <font face = "arial" size="+1">
    <?php
1       $color1 = "red";
        $color2 = "blue";
        $color3 = "yellow";
2       for($count = 1; $count <= 3; $count++){
3           $primary = "color" . $count;   // Variable variable
4           print "<font color= ${$primary}>";
            echo "The value stored in $primary: ${$primary}<br />";
5       }
    ?>
    </font>
    </body>
    </html>
04fig18.jpg

Figure 4.18 Dynamic variables. Output from Example 4.16.

Explanation

1

Three variables are defined and assigned colors. Notice the variable names only differ by the number appended to the name, 1, 2, and 3.

2

Although we haven't yet discussed loops, this is the best way to illustrate the use of variable variables (or dynamic variables). The initial value in the loop, $count, is set to 1. If the value of $count is less than 3 ($count < 3), then control goes to line 3. After the closing curly brace is reached on line 5, control will go back to the top of the loop and the value of $count will be incremented by 1. If $count is less than 3, the process repeats, and when $count reaches 3, the loop terminates.

3

The first time through the loop, the value of $count is appended to the string "color" resulting in color1. The value, "color1", is then assigned to the variable, $primary, so that $primary = color1;.

4

PHP expands ${$primary}a as follows:

${color1}

First evaluate $primary within the curly braces.

$color1

Remove the braces and now evaluate $color1 resulting in "red".

The color of the font and the text will be red. Next time through the loop, the count will go up by one ($count = 2) and the $color2 will be "blue", and finally $color3 will be "yellow".

5

See "The for Loop" on page 235 for an example of how to make use of dynamic variables with forms.

4.2.9 Scope of Variables

Scope refers to where a variable is available within a script. Scope is important because it prevents important variables from being accidentally modified in some other part of the program and thus changing the way the program behaves. PHP has specific rules to control the visibility of variables. A local variable is one that exists only within a function. A global variable is available anywhere in the script other than from within functions. (See Chapter 9, "User-Defined Functions," for creating global variables within functions.) For the most part all PHP variables have a single scope, global.

Local Variables

Variables created within a function are not available to the rest of the script. They are local to the function and disappear (go out of scope) when the function exits. If you have the same name for a variable within a function as in the main program, modifying the variable in the function will not affect the one outside the function (see Chapter 9, "User-Defined Functions"). Likewise, the function does not have access to variables created outside of the function. Most of the variables we create will be visible in the script or function in which they are declared. See Chapter 9, "User-Defined Functions," to get a full understanding of scope, including local variables, globals, superglobals, and static.

Global and Environment Variables

Superglobal variables (see Table 4.4) are accessible everywhere within a script and within functions. They are special variables provided by PHP to help you manage HTML forms, cookies, sessions, and files, and to get information about your environment and server.

Table 4.4. Some Superglobal Variables

Name

Meaning

$GLOBALS

An array of all global variables

$_SERVER

Contains server variables (e.g., REMOTE_ADDR)

$_GET

Contains form variables sent through GET method

$_POST

Contains form variables sent through POST method

$_COOKIE

Contains HTTP cookie variables

$_FILES

Contains variables provided to the script via HTTP post file uploads

$_ENV

Contains the environment variables

$_REQUEST

A merge of the GET variables, POST variables, and cookie variables

$_SESSION

Contains HTTP variables registered by the session module

4.2.10 Managing Variables

You might want to find out if a variable has been declared, you might want to delete one that has been set, or check to see if one that is set is not empty or is a string, number, scalar, and so on. PHP provides a number of functions (see Table 4.5) to help you manage variables.

Table 4.5. Functions for Managing Variables

Function

What It Returns

isset()

True if variable has been set.

empty()

True if variable is empty: "" (an empty string) "0" (a string) 0 (an integer)

is_bool()

True if variable is boolean; that is, contains TRUE or FALSE.

is_callable()

True if variable is assigned the name of a function or an object.

is_double(), is_float(), is_real()

True if variable is a floating-point number (e.g., 5.67 or .45).

is_int, is_integer, is_long

True if a variable is assigned a whole number.

is_null()

True if a variable was assigned the NULL value.

is_numeric()

True if the variable was assigned a numeric string value or a number.

is_object()

True if the variable is an object.

is_resource()

True if the variable is a resource.

is_scalar()

True if the value was assigned a single value, such as a number (e.g., "555" a string, or a boolean, but not an array or object).

is_string()

True if a variable is a string of text (e.g., "hello").

unset()

Unsets or destroys a list of values.

The isset() Function

The isset() function returns true if a variable has been set and false if it hasn't. If the variable has been set to NULL or has no value, it returns false. If you want to see if a variable has been set to NULL, use the is_null() function. To ensure that a variable has an initial value, the isset() function can be used to set a default value. See Examples 4.17 and 4.18.

Format

bool isset ( variable, variable, variable .... );

Example:

$set = isset( $name );    // returns true or false
print isset($a, $b, $c);  // prints 1 or nothing

Example 4.17.

    <html><head><title>Testing Variables</title></head>
    <body bgcolor="#66CC66">
    The <b>isset()</b> function returns a boolean value. <br />
    If one or more variables exist and have a value, true is returned;
        otherwise false.
    <font face="verdana" size="+1">
    <p />
    <?php
1       $first_name="John"; $middle_name=" "; $last_name="Doe";
2       $age;
3       $state=NULL;
4       print 'isset($first_name,$middle_name,$last_name) : ' .
               isset($first_name,$last_name) ."<br />";
5       print 'isset($age) : '. isset($age) ."<br />";
        print 'isset($city ) : '. isset($city) ."<br />";
        print 'isset($state ) : '. isset($state) ."<br />";
    ?>
    </body>
    </html>

Explanation

1

Three variables are assigned string values; $middle_name is assigned the empty string, a set of double quotes containing no text.

2

$age is declared but has not been assigned any value yet, which evaluates to NULL.

3

$state is declared and assigned the value NULL, which means it has no value.

4

The isset() function returns true if a variable has been set and given a non-null value. In this case, all three variables have a value, even the variable assigned an empty string. If true, 1 is displayed; if false, 0 or nothing is displayed.

5

Because $age was not given any value, it is implied to be null, and isset() returns false. $city was never even declared, and $state was assigned NULL; isset() returns false. If you want to check explicitly for the NULL value (case insensitive), use the built-in is_null() function (see Figure 4.19).

04fig19.jpg

Figure 4.19 Is the variable set? Output from Example 4.17.

Example 4.18.

    <html><head><title>Give a Variable a Default Value</title></head>
    <body bgcolor="66C68">
    <font face="verdana" size="+1">
    <p>
    <?php
1       if ( ! isset($temp)) { $temp = 68 ; } // Sets a default value
2       echo "The default temperature is $temp degrees.<br />";
    ?>
    </p>
    </body>
    </html>

Explanation

1

The isset() function returns true if $temp has been set. The ! operator, the unary "not" operator, reverses the boolean result. The expression reads, "if $temp is not set, define it with a value of 68."

2

The echo statement displays the default value in the browser (see Figure 4.20).

04fig20.jpg

Figure 4.20 Setting a default value. Output from Example 4.18.

The empty() Function

The empty() function returns true if a variable does not exist, or exists and has been assigned one of the following: an empty string " ", 0 as a number, "0" as a string, NULL, or no value at all. Example 4.19 demonstrates the use of the empty() function.

Format

boolean empty ( variable );

Example:

if ( empty($result) ){
print "\$result either doesn't exist or is empty\n";

Example 4.19.

    <html><head><title>Testing Variables</title></head>
    <body bgcolor="66C66">
    The <b>empty()</b> function returns a boolean value. <br />
    If a variable doesn't exist or is assigned the empty string,
    0, <br />or "0", NULL, or hasn't been assigned any value;
    returns true, otherwise false.
    <font face="verdana" size="+1">
    <p>

    <?php
1       $first_name=""; $last_name=" ";
2       $age=0;
3       $salary="0";
4       $state=NULL;
        print 'empty($first_name) : ' . empty($first_name) ."<br />";
        print 'empty($last_name) : ' . empty($last_name) ."<br />";
        print 'empty($age) : '. empty($age) ."<br />";
        print 'empty($salary) : '. empty($salary) ."<br />";
        print 'empty($state ) : '. empty($state) ."<br />";
    ?>

    </p>
    </body>
    </html>
04fig21.jpg

Figure 4.21 Is the variable empty? Output from Example 4.19.

The unset() Function

The unset() function (technically a language construct) unsets or destroys a given variable. It can take a varied number of arguments and behaves a little differently within functions (see Chapter 9, "User-Defined Functions"). As of PHP 4, it has no return value and is considered a statement.

Format

void unset ( mixed var [, mixed var [, mixed ...]] )

Example:

unset($a, $b); // unsets the variables

Example 4.20.

    <html><head><title>Testing Variables</title></head>
    <body bgcolor="66C66">
    The <b>unset()</b> function destroys a variable. <br />
    <font face="verdana" size="+1">
    <p>
    <?php
1       $first_name="John";
        $last_name="Doe";
        $age=35;
2       unset($first_name, $last_name);
        print 'After unset() was used, isset($first_name,$last_name) '. 3
           isset($first_name,$last_name). "returns false.<br />";
    ?>
    </p>
    </body>
    </html>

Explanation

1

Two scalar variables are declared and assigned string values.

2

The built-in unset() function will destroy the variables listed as arguments.

3

The isset() function returns true if a variable exists, and false if it doesn't.

04fig22.jpg

Figure 4.22 Destroying variables.

4.2.11 Introduction to Form Variables

Now we are starting to get into what makes PHP so popular. As we mentioned in the introduction to this book, PHP was designed as a Web-based programming language to create dynamic Web content, to gather and manipulate information submitted by HTML forms. For now, because we are talking about variables, we will examine a simple form and how PHP collects and stores the form information in variables. Chapter 10, "More on PHP Forms," provides a comprehensive discussion on HTML forms and introduces the special global arrays used to process them in your PHP scripts.

The php.ini File and register_globals

Before getting started, there are some issues to be aware of based on the version of PHP you are using. The PHP initialization file, called php.ini, contains a directive called register_globals. Older versions of PHP (prior to 4.2.0) had this directive turned to "On" as the default, allowing PHP to create simple variables from form data. Since then, register_globals has been set to "Off" to avoid potential security breaches. If using PHP 5, you will have to turn this feature on before PHP can directly assign form input to simple global variables, or the data must be extracted programatically. We discuss both ways to do this in the following section. The next excerpt is taken from the PHP 5 php.ini file, showing the line where register_globals is set. The default is "Off" and you should really try to adhere to this setting.

From the php.ini file:

; You should do your best to write your scripts so that they do not require
; register_globals to be on; Using form variables as globals can easily lead
; to possible security problems, if the code is not very well thought of.
register_globals = Off

If you do not set register_globals to "On," add the following line to your PHP program:

extract($_REQUEST);

The $_REQUEST superglobal array contains the information submitted to the server from the HTML form. After extracting this information, PHP will create simple variables corresponding to the form data as shown in Example 4.24. In Chapter 10, "More on PHP Forms," all aspects of extracting form data are discussed in detail. For now, assume register_globals is set to "On."

How PHP Handles Form Input

For each HTML form parameter, PHP creates a global variable by the same name and makes it available to your script. For example, consider this HTML input type for two text fields:

<input type="text" name="your_name">
<input type="text" name ="your_phone">

If you have a text field named "your_name", PHP will create a variable called $your_name. And if you have another text field named "your_phone", PHP will in turn, create a variable called $your_phone. The values assigned to the PHP variables are the same values the user entered in the HTML text fields when filling out the form.

Example 4.21 illustrates a simple HTML form consisting of two fields. The form starts with the opening <form> tag. The ACTION attribute of the form tag is assigned the name of the PHP script that will handle the form input: <form ACTION="php script">.

After the user fills out the form (see Figure 4.25) and presses the submit button, the values that he or she typed in the text boxes will be sent to the PHP script (see Example 4.22). The browser knows where to send the data based on the ACTION attribute of the <form> tag, but it also needs to know how to send the form data to the server. The how, or method, is also an attribute of the <form> tag, called the METHOD atribute. There are two popular HTTP methods used to send the form information to the server—the GET method (default) and the POST method. Because the GET method is the default, you don't have to explicitly assign it as an attribute. The browser just assumes that is the method you are using. The GET method tells the browser to send a URL-encoded string, called the query string, to the server. It attaches this encoded query string to the end of the URL in the browser's location box, prepended with a ?. It is the method used when doing searches or handling static pages and GET query strings are limited in size (see Figure 4.23).

04fig23.gif

Figure 4.23 The GET method sends form input in the URL.

If using the POST method, the METHOD attribute must be added to the HTML <form> tag METHOD="POST" (case insensitive). With the POST method, the browser sends an encoded message body in the HTTP header to the server so that it doesn't appear in the URL. It is not limited in size, but it can't be bookmarked or reloaded, and does not appear in the browser's history (see Figure 4.24).

04fig24.gif

Figure 4.24 The POST method sends form input in an HTTP header.

When PHP gets the form input from the server, it takes care of decoding the query string or message body and assigning the respective input values to PHP variables as shown in Example 4.21. (For a complete discussion of the differences between the GET and POST methods, see http://www.cs.tut.fi/~jkorpela/forms/methods.html.)

Example 4.21.

    <html>
    <head>
    <title>Simple HTML Form</title>
    </head>
    <body bgcolor="lightblue"><font size="+1">
1       <form action="http://localhost/exemples/ch4variables/
                      form_example.php" />
        <p>
        please enter your name: <br />
2       <input type="text" size=30 name="your_name" />
        <br />
3       please enter your phone number: <br />
        <input type="text" size=30 name="your_phone" />
        <br />
4       <input type=submit value="submit" />
5       </form>
    </body>
    </html>

Explanation

1

The HTML <form> tag starts the form. The URL of the script that will handle the form data is assigned to the action attribute. The "method" on how the data will be transmitted is assigned to the method attribute. Because the GET method is the default method for transmitting data to the server, you do not have to explicitly assign it as an attribute. This example is using the GET method.

2, 3

The HTML input type is a text box that is set to hold 50 characters. One is named "your_name" and the other is named "your_phone".

4

After the user enters his or her name and phone number in the respective text boxes, and presses the submit button (see Figure 4.25), the browser will collect and URL encode the input data, then send it to the server. The server will hand it to the PHP script listed (see Example 4.22) in the action attribute on line 1. When PHP gets the input data, it will decode it, and create a variable called $your_name (the name of the first text box) and a variable called $your_phone (the name of the second text box) and give it the values that were entered in the form by the user.

5

This </form> tag ends the HTML form.

04fig25.jpg

Figure 4.25 The HTML form has been filled out by a user.

Example 4.22.

(The PHP Script)

    <?php
    extract($_REQUEST);
1   print "Your phone number is $your_name. <br />";
    print "Your phone number is $your_phone.";
    ?>

or in the HTML document use the PHP shortcut tags:

    <html><head><title>Testing Variables</title></head>
    <body>
2   Your phone number is <?=$your_name?> and your phone number is
              <?=$your_phone?>
    </body></html>

Explanation

1

The browser bundles up the input data, encodes it, and attaches it as a query string to the URL as:

?http://localhost/exemples/ch4variables/form_example.php?
your_name=Samual+B.+Johnson+Jr.&your_phone=222-444-8888

PHP decodes the query string; that is, it removes the + signs and & and any other encoding characters, and then creates global variables, called $your_name and $your_phone, and assigns values based on the user input. In this example, the values of the variables are printed as part of the PHP script.

2

You can also use the shortcut tags within the HTML document to display the value of the PHP variables. The output is displayed in the browser, as shown in Figure 4.26.

04fig26.jpg

Figure 4.26 Output from the PHP script in Example 4.22. The input data is appended to the URL after the ?.

Extracting the Data by Request

In the previous example, we used the default GET method to send form input to the server. We also assumed the register_globals in the php.ini file was turned "On," allowing PHP to create simple global variables with the form data. In the following example, we assume that register_globals is turned "Off" (the recommended and default setting) and that the method is POST, the more commonly used method when working with form input, as shown in Figure 4.24. This method sends the form input as a message body in the HTTP header to the server and does not append the data to the URL in the browser. Even though the input data is sent using a different method, it is received in the same URL-encoded format. When register_globals is turned off, PHP provides special variables, called arrays, to store the form information. Because we do not cover arrays until Chapter 8, "Arrays," we will create simple variables to hold input data from the form, but first must explicitly extract the data from a special global array called $_REQUEST. This special array contains all of the input data for both GET and POST methods, and once it is extracted will be assigned to PHP variables with the same name as was given to the corresponding input devices in the HTML form.

Example 4.23.

(The HTML Form Source)

    <html>
    <head>
    <title>First HTML Form</title>
    </head>
    <body bgcolor="lightblue"><font size="+1">
1       <form action="/phpforms/form1.php" method="POST">
        <p>
        Please enter your name: <br />
2       <input type="text" size=50 name="your_name">
        <p>
        Please enter your phone: <br />
3       <input type="text" size=50 name="your_phone">
        <p>
        Please enter your email address:<br />
4       <input type="text" size=50 name="your_email_addr">
        <p>
5       <input type=submit value="submit">
        <input type=reset value="clear">
6       </form>
    <hr>
    </body>
    </html>

Explanation

1

The HTML <form> tag starts the form. The URL of the script that will handle the form data is assigned to the action attribute. The "method" on how the data will be transmitted is assigned to the method attribute. The POST method is used here. This is the most common method for processing forms. The form input is sent in an HTTP header to the server.

2, 3, 4

The input devices are three text boxes for accepting user input. The name attribute is assigned the names of the respective boxes, your_name, your_phone, and your_email (see Figure 4.27). These same names will be used as variable names in the PHP program, /phpforms/form1.php, listed in the forms action attribute.

5

When the user presses the submit button, the form input is encoded and sent to the server. The form input will not be visible in the URL as it is with the GET method.

6

This marks the end of the form.

04fig27.jpg

Figure 4.27 Data has been entered into the HTML form.

Example 4.24.

(The PHP program)

    <html><head><title>Processing First Form</title>
    </head>
    <body bgcolor = "lightgreen"><font size="+1">
    <h2>Here is the form input:</h2>
    <?php
1       extract($_REQUEST, EXTR_SKIP);   // Extracting the form input
        print "Welcome to PHP $your_name<br />"; // register_globals
                                                  // is off
        print "Can I call you at $your_phone<br />";
        print "Is it ok to send you email at $your_email_addr<br />";
    ?>
    </body>
    </html>

Explanation

1

If the register_globals directive in the php.ini file is set to "Off," the built-in PHP extract() function can be used to get the form input stored in $_REQUEST, an array that contains input recieved from both GET and POST methods. The extract() function will convert the input into variables of the same name as the input devices in the HTML file. The EXTR_SKIP flag ensures that if there is a collision, that is, you have already defined a variable with the that name somewhere in your PHP program, it won't be overwritten.

2

The variables $your_name, $your_phone, and $your_email_addr were created by the extract() function and named after the text boxes originally named in the HTML form. The output is displayed in the browser, as in Figure 4.28.

04fig28.jpg

Figure 4.28 After PHP processes the input data from the form.

Predefined Variables

PHP provides a number of predefined variables (see Table 4.6 and Figure 4.29), some that are not fully documented because they depend on which server is running, its configuration, and so on. Some are defined in the php.ini file. These variables describe the environment, server, browser, version number, configuration file, and so on.

Table 4.6. Predefined Variablesa

Variable

What It Does

AUTH_TYPE

If running the Apache server as a module, this is set to the authentication type.

DOCUMENT_ROOT

The full path of the Web's document root, normally where HTML pages are stored and defined in the server's configuration file.

HTTP_USER_AGENT

Identifies the type of Web browser to the server when it requests a file.

HTTP_REFERER

The full URL of the page that contained the link to this page. Of course if there isn't a referring page, this variable would not exist.

REMOTE ADDRESS

The remote IP address of the client machine that requested the page.

04fig29.jpg

Figure 4.29 PHP variables (partial output from the phpinfo() function).

There many more predefined variables; which ones are set depends on your PHP configuration. The function phpinfo() can be used to retrieve built-in variables that have been set.

<?php
phpinfo(INFO_VARIABLES);
?>
  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020