1: <html>
2: <head>
3: <title>Listing 5.3</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: if ( $mood == "happy" )
9: {
10: print "Hooray, I'm in a good mood";
11: }
12: elseif ( $mood == "sad" )
13: {
14: print "Awww. Don't be down!";
15: }
16: else
17: {
18: print "Neither happy nor sad but $mood";
19: }
20: ?>
21: </body>
22: </html>
Once again, $mood holds a string, "sad". This is not equivalent to "happy", so the
first block is ignored. The elseif clause tests for equivalence between the contents of
$mood and "sad", which evaluates to true. This block of code is therefore executed.
The switch Statement
The switch statement is an alternative way of changing program flow according to
the evaluation of an expression. There are some key differences between the switch
and if statements. Using the if statement in conjunction with elseif, you may
evaluate multiple expressions. switch evaluates only one expression, executing
different code according to the result of that expression, as long as the expression
evaluates to a simple type (a number, a string, or a boolean). The result of an
expression evaluated as part of an if statement is read as either true or false. The
expression of a switch statement yields a result that is tested against any number of
values.
switch ( expression )
{
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
The switch statement's expression is often simply a variable. Within the switch
statement's block of code, you find a number of case statements. Each of these
tests a value against the result of the switch statement's expression. If these are
equivalent, then the code after the case statement is executed. The break
statement ends execution of the switch statement altogether. If this is left out, the
next case statement's expression is evaluated. If the optional default statement is
reached, its code is executed.
Caution Don't forget to include a break statement at the end of any code that
will be executed as part of a case statement. Without break, the
program flow will continue to the next case statement and ultimately
to the default statement. In most cases, this will not be the behavior
that you will be expecting.
Wednesday, 8 July 2015
Using the else Clause with the if Statement
When working with the if statement, you will often want to define an alternative
block of code that should be executed if the expression you are testing evaluates to
false. You can do this by adding else to the if statement followed by a further block
of code:
if ( expression )
{
// code to execute if the expression evaluates to true
}
else
{
// code to execute in all other cases
}
Listing 5.2 amends the example in Listing 5.1 so that a default block of code is
executed if $mood is not equivalent to "happy".
Listing 5.2: An if Statement That Uses else
1: <html>
2: <head>
3: <title>Listing 5.2</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: if ( $mood == "happy" )
9: {
10: print "Hooray, I'm in a good mood";
11: }
12: else
13: {
14: print "Not happy but $mood";
15: }
16: ?>
17: </body>
18: </html>
$mood contains the string "sad", which is not equivalent to "happy", so the
expression in the if statement evaluates to false. This means that the first block of
code is skipped. The block of code after else, therefore, is executed, and the
message "Not happy but sad" is printed to the browser.
Using the else clause with the if statement allows scripts to make sophisticated
decisions, but you currently are limited to an either -or branch. PHP4 allows you to
evaluate multiple expressions in a cascade.
Using the elseif Clause with the if Statement
You can use an if-elseif-else construct to test multiple expressions before offering a
default block of code:
if ( expression )
{
// code to execute if the expression evaluates to true
}
elseif ( another expression )
{
// code to execute if the previous expression failed
// and this one evaluates to true
else
{
// code to execute in all other cases
}
If the first expression does not evaluate to true, then the first block of code is
ignored. The elseif clause then causes another expression to be evaluated. Once
again, if this expression evaluates to true, then the second block of code is executed.
Otherwise, the block of code associated with the else clause is executed. You can
include as many elseif clauses as you want, and if you don't need a default action,
you can omit the else clause.
block of code that should be executed if the expression you are testing evaluates to
false. You can do this by adding else to the if statement followed by a further block
of code:
if ( expression )
{
// code to execute if the expression evaluates to true
}
else
{
// code to execute in all other cases
}
Listing 5.2 amends the example in Listing 5.1 so that a default block of code is
executed if $mood is not equivalent to "happy".
Listing 5.2: An if Statement That Uses else
1: <html>
2: <head>
3: <title>Listing 5.2</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: if ( $mood == "happy" )
9: {
10: print "Hooray, I'm in a good mood";
11: }
12: else
13: {
14: print "Not happy but $mood";
15: }
16: ?>
17: </body>
18: </html>
$mood contains the string "sad", which is not equivalent to "happy", so the
expression in the if statement evaluates to false. This means that the first block of
code is skipped. The block of code after else, therefore, is executed, and the
message "Not happy but sad" is printed to the browser.
Using the else clause with the if statement allows scripts to make sophisticated
decisions, but you currently are limited to an either -or branch. PHP4 allows you to
evaluate multiple expressions in a cascade.
Using the elseif Clause with the if Statement
You can use an if-elseif-else construct to test multiple expressions before offering a
default block of code:
if ( expression )
{
// code to execute if the expression evaluates to true
}
elseif ( another expression )
{
// code to execute if the previous expression failed
// and this one evaluates to true
else
{
// code to execute in all other cases
}
If the first expression does not evaluate to true, then the first block of code is
ignored. The elseif clause then causes another expression to be evaluated. Once
again, if this expression evaluates to true, then the second block of code is executed.
Otherwise, the block of code associated with the else clause is executed. You can
include as many elseif clauses as you want, and if you don't need a default action,
you can omit the else clause.
Labels:
Comments,
Environment,
join,
mysql,
php,
programmers,
variables,
Workshop
Going with the Flow
Overview
The scripts created in the last hour flow only in a single direction. The same
statements are executed in the same order every time a script is run. This does not
leave much room for flexibility.
You now will look at some structures that enable your scripts to adapt to
circumstances. In this hour, you will learn
How to use the if statement to execute code only if a test expression evaluates
to true
How to execute alternative blocks of code when the test expression of an if
statement evaluates to false
How to use the switch statement to execute code based on the value returned by
a test expression
How to repeat execution of code using a while statement
How to use for statements to make neater loops
How to break out of loops
How to nest one loop within another
Switching Flow
Most scripts evaluate conditions and change their behavior accordingly. The facility
to make decisions makes your PHP pages dynamic, capable of changing their output
according to circumstances. Like most programming languages, PHP4 allows you to
do this with an if statement.
The if Statement
The if statement evaluates an expression between parentheses. If this expression
results in a true value, a block of code is executed. Otherwise, the block is skipped
entirely. This enables scripts to make decisions based on any number of factors.
if ( expression )
{
// code to execute if the expression evaluates to true
}
Listing 5.1 executes a block of code only if a variable contains the string "happy".
Listing 5.1: An if Statement
1: <html>
2: <head>
3: <title>Listing 5.1</title>
4: </head>
5: <body>
6: <?php
7: $mood = "happy";
8: if ( $mood == "happy" )
9: {
10: print "Hooray, I'm in a good mood";
11: }
12: ?>
13: </body>
14: </html>
You use the comparison operator == to compare the variable $mood with the string
"happy". If they match, the expression evaluates to true, and the code block below
the if statement is executed. Although the code block is wrapped in braces in the
example, this is only necessary if the block contains more than one line. The
following fragment, therefore, would be acceptable:
if ( $mood == "happy" )
print "Hooray, I'm in a good mood";
If you change the value of $mood to "sad" and run the script, the expression in the
if statement evaluates to false, and the code block is skipped. The script remains
sulkily silent.
The scripts created in the last hour flow only in a single direction. The same
statements are executed in the same order every time a script is run. This does not
leave much room for flexibility.
You now will look at some structures that enable your scripts to adapt to
circumstances. In this hour, you will learn
How to use the if statement to execute code only if a test expression evaluates
to true
How to execute alternative blocks of code when the test expression of an if
statement evaluates to false
How to use the switch statement to execute code based on the value returned by
a test expression
How to repeat execution of code using a while statement
How to use for statements to make neater loops
How to break out of loops
How to nest one loop within another
Switching Flow
Most scripts evaluate conditions and change their behavior accordingly. The facility
to make decisions makes your PHP pages dynamic, capable of changing their output
according to circumstances. Like most programming languages, PHP4 allows you to
do this with an if statement.
The if Statement
The if statement evaluates an expression between parentheses. If this expression
results in a true value, a block of code is executed. Otherwise, the block is skipped
entirely. This enables scripts to make decisions based on any number of factors.
if ( expression )
{
// code to execute if the expression evaluates to true
}
Listing 5.1 executes a block of code only if a variable contains the string "happy".
Listing 5.1: An if Statement
1: <html>
2: <head>
3: <title>Listing 5.1</title>
4: </head>
5: <body>
6: <?php
7: $mood = "happy";
8: if ( $mood == "happy" )
9: {
10: print "Hooray, I'm in a good mood";
11: }
12: ?>
13: </body>
14: </html>
You use the comparison operator == to compare the variable $mood with the string
"happy". If they match, the expression evaluates to true, and the code block below
the if statement is executed. Although the code block is wrapped in braces in the
example, this is only necessary if the block contains more than one line. The
following fragment, therefore, would be acceptable:
if ( $mood == "happy" )
print "Hooray, I'm in a good mood";
If you change the value of $mood to "sad" and run the script, the expression in the
if statement evaluates to false, and the code block is skipped. The script remains
sulkily silent.
Defining a Constant
<html>
2: <head>
3: <title>Listing 4.7 Defining a constant</title>
4: </head>
5: <body>
6: <?php
7: define ( "USER", "Gerald" );
8: print "Welcome ".USER;
9: ?>
10: </body>
11: </html>
Notice that we used the concatenation operator to append the value held by our
constant to the string "Welcome". This is because the interpreter has no way of
distinguishing between a constant and a string within quotation marks.
Predefined Constants
PHP automatically provides some built-in constants for you. __FILE__, for example,
returns the name of the file currently being read by the interpreter. __LINE__
returns the line number of the file. These constants are useful for generating error
messages. You can also find out which version of PHP is interpreting the script with
PHP_VERSION. This can be useful if you want to limit a script to run on a particular
PHP release.
Summary
In this hour, you covered some of the basic features of the PHP language. You
learned about variables and how to assign to them using the assignment operator.
You learned about dynamic or "variable" variables. You also learned how to assign
to variables by reference rather than by value. You were introduced to operators
and learned how to combine some of the most common of these into expressions.
Finally, you learned how to define and access constants.
to make sure that a variable contains an integer or a double before using it in a
mathematical calculation, for example.
You explore situations of this kind a little further in Hour 16, "Working with Data."
A variable such as $ab123245 tells you nothing about its role in your script and
invites typos. Keep your variable names short and descriptive.
A variable named $f is unlikely to mean much to you when you return to your code
after a month or so. A variable named $filename, on the other hand, should make
more sense.
tasks. By using parentheses in your expressions, you can make your code easy to
read at the same time as defining your own order of precedence.
Workshop
The Workshop provides quiz questions to help you solidify your understanding of the
material covered. Try to understand the quiz answers before continuing to the next
hour's lesson. Quiz answers are provided in Appendix A.
Quiz
$666666xyz
$xyz666666
$_____counter____
$the first
$file-name
How could you use the string variable created in the assignment expression
$my_var = "dynamic";
to create a "variable" variable, assigning the integer 4 to it. How might you access
this new variable?
What will the following statement output?
print gettype("4");
What will be the output from the following code fragment?
$test_val = 5.4566;
settype( $test_val, "integer" );
print $test_val;
Which of the following statements does not contain an expression?
4;
gettype(44);
5/12;
Which of the statements in question 5 contains an operator?
What value will the following expression return?
5 < 2
What data type will the returned value be?
Activities
Create a script that contains at least five different variables. Populate them with
values of different data types and use the gettype() function to print each type to
the browser.
Assign values to two variables. Use comparison operators to test whether the
first value is
The same as the second
Less than the second
Greater than the second
Less than or equal to the second
Print the result of each test to the browser.
Change the values assigned to your test variables and run the script again.
2: <head>
3: <title>Listing 4.7 Defining a constant</title>
4: </head>
5: <body>
6: <?php
7: define ( "USER", "Gerald" );
8: print "Welcome ".USER;
9: ?>
10: </body>
11: </html>
Notice that we used the concatenation operator to append the value held by our
constant to the string "Welcome". This is because the interpreter has no way of
distinguishing between a constant and a string within quotation marks.
Predefined Constants
PHP automatically provides some built-in constants for you. __FILE__, for example,
returns the name of the file currently being read by the interpreter. __LINE__
returns the line number of the file. These constants are useful for generating error
messages. You can also find out which version of PHP is interpreting the script with
PHP_VERSION. This can be useful if you want to limit a script to run on a particular
PHP release.
Summary
In this hour, you covered some of the basic features of the PHP language. You
learned about variables and how to assign to them using the assignment operator.
You learned about dynamic or "variable" variables. You also learned how to assign
to variables by reference rather than by value. You were introduced to operators
and learned how to combine some of the most common of these into expressions.
Finally, you learned how to define and access constants.
Q&A
Q Why can it be useful to know the type of data a variable holds?
A Often the data type of a variable constrains what you can do with it. You may wantto make sure that a variable contains an integer or a double before using it in a
mathematical calculation, for example.
You explore situations of this kind a little further in Hour 16, "Working with Data."
Q Should I obey any conventions when naming variables?
A Your goal should always be to make your code both easy to read and understand.A variable such as $ab123245 tells you nothing about its role in your script and
invites typos. Keep your variable names short and descriptive.
A variable named $f is unlikely to mean much to you when you return to your code
after a month or so. A variable named $filename, on the other hand, should make
more sense.
Q Should I learn the operator precedence table?
A There is no reason why you shouldn't, but I would save the effort for more usefultasks. By using parentheses in your expressions, you can make your code easy to
read at the same time as defining your own order of precedence.
Workshop
The Workshop provides quiz questions to help you solidify your understanding of the
material covered. Try to understand the quiz answers before continuing to the next
hour's lesson. Quiz answers are provided in Appendix A.
Quiz
Which of the following variable names is not valid?
$a_value_submitted_by_a_user$666666xyz
$xyz666666
$_____counter____
$the first
$file-name
How could you use the string variable created in the assignment expression
$my_var = "dynamic";
to create a "variable" variable, assigning the integer 4 to it. How might you access
this new variable?
What will the following statement output?
print gettype("4");
What will be the output from the following code fragment?
$test_val = 5.4566;
settype( $test_val, "integer" );
print $test_val;
Which of the following statements does not contain an expression?
4;
gettype(44);
5/12;
Which of the statements in question 5 contains an operator?
What value will the following expression return?
5 < 2
What data type will the returned value be?
Activities
Create a script that contains at least five different variables. Populate them with
values of different data types and use the gettype() function to print each type to
the browser.
Assign values to two variables. Use comparison operators to test whether the
first value is
The same as the second
Less than the second
Greater than the second
Less than or equal to the second
Print the result of each test to the browser.
Change the values assigned to your test variables and run the script again.
Tuesday, 7 July 2015
Logical Operators
Operator Name Returns
True if…
Example Result
|| Or Left or right
is true
true || false true
or Or Left or right
is true
true || false true
xor Xor Left or right
is true but
not both
true || true false
&& And Left and
right are
true
true && false false
and And Left and
right are
true
true && false false
! Not The single
operand is
not true
! true false
Why are there two versions of both the or and the and operators? The answer lies in
operator precedence, which you will look at later in this section.
Automatically Incrementing and Decrementing an Integer Variable
When coding in PHP, you will often find it necessary to increment or decrement an
integer variable. You will usually need to do this when you are counting the
iterations of a loop. You have already learned two ways of doing this. I could
increment the integer contained by $x with the addition operator
$x = $x + 1; // $x is incremented
or with a combined assignment operator
$x += 1; // $x is incremented
In both cases, the resultant integer is assigned to $x. Because expressions of this
kind are so common, PHP provides some special operators that allow you to add or
subtract the integer constant 1 from an integer variable, assigning the result to the
variable itself. These are known as the post-increment and post-decrement
operators. The post-increment operator consists of two plus symbols appended to a
variable name.
$x++; // $x is incremented
increments the variable $x by one. Using two minus symbols in the same way
decrements the variable:
$x− − ; // $x is decremented
If you use the post-increment or post-decrement operators in conjunction with a
conditional operator, the operand will only be modified after the test has been
completed:
$x = 3;
$x++ < 4; // true
In the previous example, $x contains 3 when it is tested against 4 with the less than
operator, so the test expression returns true. After this test is complete, $x is
incremented.
In some circumstances, you might want to increment or decrement a variable in a
test expression before the test is carried out. PHP provides the pre -increment and
pre-decrement operators for this purpose. On their own, these operators behave in
exactly the same way as the post-increment and post-decrement operators. They
are written with the plus or minus symbols preceding the variable:
++$x; // $x is incremented
− − $x; // $x is decremented
If these operators are used as part of a test expression, the incrementation occurs
before the test is carried out.
$x = 3;
++$x < 4; // false
In the previous fragment, $x is incremented before it is tested against 4. The test
expression returns false because 4 is not smaller than 4.
Operator Precedence
When you use an operator, the interpreter usually reads your expression from left to
right. For complex expressions that use more than one operator, though, the waters
can become a little murky. First, consider a simple case:
4 + 5
There's no room for confusion, here. PHP simply adds 4 to 5. What about the next
fragment?
4 + 5 * 2
This presents a problem. Does it mean the sum of 4 and 5, which should then be
multiplied by 2, giving the result 18? Does it mean 4 plus the result of 5 multiplied
by 2, resolving to 14? If you were to read simply from left to right, the former would
be true. In fact, PHP attaches different precedence to operators. Because the
multiplication operator has higher precedence than the addition operator does, the
second solution to the problem is the correct one.
You can force PHP to execute the addition expression before the multiplication
expression with parentheses:
( 4 + 5 ) * 2
Whatever the precedence of the operators in a complex expression, it is a good idea
to use parentheses to make your code clearer and to save you from obscure bugs.
Table 4.6 lists the operators covered in this hour in precedence order (highest first).
Table 4.6: Order of Precedence for Selected Operators
Operators
++ − − (cast)
/ *%
+ −
< <= => >
== === !=
&&
||
= += − = /= *=%= .=
and
xor
or
As you can see, or has a lower precedence than || and and has a lower precedence
than &&, so you could use the lower-precedence logical operators to change the way
a complex test expression is read. This is not necessarily a good idea. The following
two expressions are equivalent, but the second is much easier to read:
$x and $y || $z
( $x && $y ) || $z
Constants
Variables offer a flexible way of storing data. You can change their values and the
type of data they store at any time. If, however, you want to work with a value that
you do not want to alter throughout your script's execution, you can define a
constant. You must use PHP's built-in function define() to create a constant. After
you have done this, the constant cannot be changed. To use the define() function,
you must place the name of the constant and the value you want to give it within the
call's parentheses:
define( "CONSTANT_NAME", 42 );
The value you want to set can only be a number or a string. By convention, the
name of the constant should be in capitals. Constants are accessed with the
constant name only; no dollar symbol is required. Listing 4.7 defines and accesses
a constan
True if…
Example Result
|| Or Left or right
is true
true || false true
or Or Left or right
is true
true || false true
xor Xor Left or right
is true but
not both
true || true false
&& And Left and
right are
true
true && false false
and And Left and
right are
true
true && false false
! Not The single
operand is
not true
! true false
Why are there two versions of both the or and the and operators? The answer lies in
operator precedence, which you will look at later in this section.
Automatically Incrementing and Decrementing an Integer Variable
When coding in PHP, you will often find it necessary to increment or decrement an
integer variable. You will usually need to do this when you are counting the
iterations of a loop. You have already learned two ways of doing this. I could
increment the integer contained by $x with the addition operator
$x = $x + 1; // $x is incremented
or with a combined assignment operator
$x += 1; // $x is incremented
In both cases, the resultant integer is assigned to $x. Because expressions of this
kind are so common, PHP provides some special operators that allow you to add or
subtract the integer constant 1 from an integer variable, assigning the result to the
variable itself. These are known as the post-increment and post-decrement
operators. The post-increment operator consists of two plus symbols appended to a
variable name.
$x++; // $x is incremented
increments the variable $x by one. Using two minus symbols in the same way
decrements the variable:
$x− − ; // $x is decremented
If you use the post-increment or post-decrement operators in conjunction with a
conditional operator, the operand will only be modified after the test has been
completed:
$x = 3;
$x++ < 4; // true
In the previous example, $x contains 3 when it is tested against 4 with the less than
operator, so the test expression returns true. After this test is complete, $x is
incremented.
In some circumstances, you might want to increment or decrement a variable in a
test expression before the test is carried out. PHP provides the pre -increment and
pre-decrement operators for this purpose. On their own, these operators behave in
exactly the same way as the post-increment and post-decrement operators. They
are written with the plus or minus symbols preceding the variable:
++$x; // $x is incremented
− − $x; // $x is decremented
If these operators are used as part of a test expression, the incrementation occurs
before the test is carried out.
$x = 3;
++$x < 4; // false
In the previous fragment, $x is incremented before it is tested against 4. The test
expression returns false because 4 is not smaller than 4.
Operator Precedence
When you use an operator, the interpreter usually reads your expression from left to
right. For complex expressions that use more than one operator, though, the waters
can become a little murky. First, consider a simple case:
4 + 5
There's no room for confusion, here. PHP simply adds 4 to 5. What about the next
fragment?
4 + 5 * 2
This presents a problem. Does it mean the sum of 4 and 5, which should then be
multiplied by 2, giving the result 18? Does it mean 4 plus the result of 5 multiplied
by 2, resolving to 14? If you were to read simply from left to right, the former would
be true. In fact, PHP attaches different precedence to operators. Because the
multiplication operator has higher precedence than the addition operator does, the
second solution to the problem is the correct one.
You can force PHP to execute the addition expression before the multiplication
expression with parentheses:
( 4 + 5 ) * 2
Whatever the precedence of the operators in a complex expression, it is a good idea
to use parentheses to make your code clearer and to save you from obscure bugs.
Table 4.6 lists the operators covered in this hour in precedence order (highest first).
Table 4.6: Order of Precedence for Selected Operators
Operators
++ − − (cast)
/ *%
+ −
< <= => >
== === !=
&&
||
= += − = /= *=%= .=
and
xor
or
As you can see, or has a lower precedence than || and and has a lower precedence
than &&, so you could use the lower-precedence logical operators to change the way
a complex test expression is read. This is not necessarily a good idea. The following
two expressions are equivalent, but the second is much easier to read:
$x and $y || $z
( $x && $y ) || $z
Constants
Variables offer a flexible way of storing data. You can change their values and the
type of data they store at any time. If, however, you want to work with a value that
you do not want to alter throughout your script's execution, you can define a
constant. You must use PHP's built-in function define() to create a constant. After
you have done this, the constant cannot be changed. To use the define() function,
you must place the name of the constant and the value you want to give it within the
call's parentheses:
define( "CONSTANT_NAME", 42 );
The value you want to set can only be a number or a string. By convention, the
name of the constant should be in capitals. Constants are accessed with the
constant name only; no dollar symbol is required. Listing 4.7 defines and accesses
a constan
Casting a Variable
Changing Type by Casting
By placing the name of a data type in brackets in front of a variable, you create a
copy of that variable's value converted to the data type specified. The principal
difference between settype() and a cast is the fact that casting produces a copy,
leaving the original variable untouched. Listing 4.6 illustrates this.
Listing 4.6: Casting a Variable
1: <html>
2: <head>
3: <title>Listing 4.6 Casting a variable</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: $holder = ( double ) $undecided;
9: print gettype( $holder ) ; // double
10: print " -- $holder<br>"; // 3.14
11: $holder = ( string ) $undecided;
12: print gettype( $holder ); // string
13: print " -- $holder<br>"; // 3.14
14: $holder = ( integer ) $undecided;
15: print gettype( $holder ); // integer
16: print " -- $holder<br>"; // 3
17: $holder = ( double ) $undecided;
18: print gettype( $holder ); // double
19: print " -- $holder<br>"; // 3.14
20: $holder = ( boolean ) $undecided;
21: print gettype( $holder ); // boolean
22: print " -- $holder<br>"; // 1
23: ?>
24: </body>
25: </html>
We never actually change the type of $undecided, which remains a double
throughout. In fact, by casting $undecided, we create a copy that is then converted
to the type we specify. This new value is then stored in the variable $holder.
Because we are working with a copy of $undecided, we never discard any
information from it as we did in Listing 4.5.
Operators and Expressions
You can now assign data to variables. You can even investigate and change the data
type of a variable. A programming language isn't very useful, though, unless you
can manipulate the data you can store. Operators are symbols that make it possible
to use one or more values to produce a new value. A value that is operated on by an
operator is referred to as an operand.
NEW
TERM
An operator is a symbol or series of symbols that, when used in
conjunction with values, performs an action and usually produces a
new value.
NEW
TERM
An operand is a value used in conjunction with an operator. There
are usually two operands to one operator.
Let's combine two operands with an operator to produce a new value:
4 + 5
4 and 5 are operands. They are operated on by the addition operator (+) to produce
9. Operators almost always sit between two operands, though you will see a few
exceptions later in this hour.
The combination of operands with an operator to manufacture a result is called an
expression. Although most operators form the basis of expressions, an expression
need not contain an operator. In fact in PHP, an expression is defined as anything
that resolves to a value. This includes integer constants such as 654, variables such
as $user, and function calls such as gettype(). The expression (4 + 5), therefore is
an expression that consists of two further expressions and an operator.
NEW
TERM
An expression is any combination of functions, values, and
operators that resolve to a value. As a rule of thumb, if you can use
it as if it were a value, it is an expression.
Now that we have the principles out of the way, it's time to take a tour of PHP4's
more common operators.
The Assignment Operator
You have met the assignment operator each time we have initialized a variable. It
consists of the single character =. The assignment operator takes the value of its
right-hand operand and assigns it to its left-hand operand:
$name ="matt";
The variable $name now contains the string "matt". Interestingly, this construct is
an expression. It might look at first glance that the assignment operator simply
changes the variable $name without producing a value, but in fact, a statement that
uses the assignment operator always resolves to a copy of the value of the right
operand. Thus
print ( $name = "matt" );
prints the string "matt" to the browser in addition to assigning "matt" to $name.
Arithmetic Operators
The arithmetic operators do exactly what you would expect. Table 4.2 lists these
operators. The addition operator adds the right operand to the left operand. The
subtraction operator subtracts the right-hand operand from the left. The division
operator divides the left-hand operand by the right. The multiplication operator
multiplies the left-hand operand by the right. The modulus operator returns the
remainder of the left operand divided by the right.
Table 4.2: Arithmetic Operators
Operator Name Example Example Result
+ Addition 10+3 13
− Subtraction 10− 3 7
/ Division 10/3 3.3333333333333
* Multiplication 10*3 30
% Modulus 10%3 1
The Concatenation Operator
The concatenation operator is a single dot. Treating both operands as strings, it
appends the right-hand operand to the left. So
"hello"." world"
returns
"hello world"
Regardless of the data types of the operands, they are treated as strings, and the
result always is a string.
More Assignment Operators
Although there is really only one assignment operator, PHP4 provides a number of
combination operators that transform the left-hand operand as well as return a
result. As a rule, operators use their operands without changing their values.
Assignment operators break this rule. A combined assignment operator consists of
a standard operator symbol followed by an equals sign. Combination assignment
operators save you the trouble of using two operators yourself. For example,
$x = 4;
$x += 4; // $x now equals 8
is equivalent to
$x = 4;
$x = $x + 4; // $x now equals 8
There is an assignment operator for each of the arithmetic operators and one for the
concatenation operator. Table 4.3 lists some of the most common.
Table 4.3: Some Combined Assignment Operators
Operator Example Equivalent to
+= $x += 5 $x = $x + 5
− = $x − = 5 $x = $x − 5
/= $x /= 5 $x = $x / 5
*= $x *= 5 $x = $x * 5
%= $x%=5 $x = $x % 5
.= $x .= "test" $x = $x" test"
Each of the examples in Table 4.3 transforms the value of $x using the value of the
right-hand operand.
Comparison Operators
Comparison operators perform tests on their operands. They return the boolean
value true if the test is successful, or false otherwise. This type of expression is
useful in control structures, such as if and while statements. You will meet these in
Hour 5.
To test whether the value contained in $x is smaller than 5, for example, you would
use the less than operator:
$x < 5
If $x contained 3, this expression would be equivalent to the value true. If $x
contained 7, the expression would resolve to false.
Table 4.4 lists the comparison operators.
Table 4.4: Comparison Operators
Operator Name Returns
True if
Example Result
== Equivalence Left is
equivalent
to right
$x == 5 false
!= Non-equivalence Left is not
equivalent
to right
$x != 5 true
=== Identical Left is
equivalent
to right and
they are the
same type
$x === 5 false
> Greater Left is than
greater
than right
$x >4 false
>= Greater than or
equal to
Left is
greater
than or
equal to
right
$x >= 4 true
< Less than Left is less
than right
x < 4 false
<= Less than or equal
to
Left is less
than or
equal to
right
$x <= 4 true
These operators are most commonly used with integers or doubles, although the
equivalence operator is also used to compare strings.
Creating More Complex Test Expressions with the Logical Operators
The logical operators test combinations of booleans. The or operator, for example
returns true if either the left or the right operand is true.
true || false
would return true.
The and operator only returns true if both the left and right operands are true.
true && false
would return false. It's unlikely that you would use a logical operator to test boolean
constants, however. It would make more sense to test two or more expressions that
resolve to a boolean. For example,
( $x > 2 ) && ( $x < 15 )
would return true if $x contained a value that is greater than 2 and smaller than 15.
We include the parentheses to make the code easier to read. Table 4.5 lists the
logical operators.
By placing the name of a data type in brackets in front of a variable, you create a
copy of that variable's value converted to the data type specified. The principal
difference between settype() and a cast is the fact that casting produces a copy,
leaving the original variable untouched. Listing 4.6 illustrates this.
Listing 4.6: Casting a Variable
1: <html>
2: <head>
3: <title>Listing 4.6 Casting a variable</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: $holder = ( double ) $undecided;
9: print gettype( $holder ) ; // double
10: print " -- $holder<br>"; // 3.14
11: $holder = ( string ) $undecided;
12: print gettype( $holder ); // string
13: print " -- $holder<br>"; // 3.14
14: $holder = ( integer ) $undecided;
15: print gettype( $holder ); // integer
16: print " -- $holder<br>"; // 3
17: $holder = ( double ) $undecided;
18: print gettype( $holder ); // double
19: print " -- $holder<br>"; // 3.14
20: $holder = ( boolean ) $undecided;
21: print gettype( $holder ); // boolean
22: print " -- $holder<br>"; // 1
23: ?>
24: </body>
25: </html>
We never actually change the type of $undecided, which remains a double
throughout. In fact, by casting $undecided, we create a copy that is then converted
to the type we specify. This new value is then stored in the variable $holder.
Because we are working with a copy of $undecided, we never discard any
information from it as we did in Listing 4.5.
Operators and Expressions
You can now assign data to variables. You can even investigate and change the data
type of a variable. A programming language isn't very useful, though, unless you
can manipulate the data you can store. Operators are symbols that make it possible
to use one or more values to produce a new value. A value that is operated on by an
operator is referred to as an operand.
NEW
TERM
An operator is a symbol or series of symbols that, when used in
conjunction with values, performs an action and usually produces a
new value.
NEW
TERM
An operand is a value used in conjunction with an operator. There
are usually two operands to one operator.
Let's combine two operands with an operator to produce a new value:
4 + 5
4 and 5 are operands. They are operated on by the addition operator (+) to produce
9. Operators almost always sit between two operands, though you will see a few
exceptions later in this hour.
The combination of operands with an operator to manufacture a result is called an
expression. Although most operators form the basis of expressions, an expression
need not contain an operator. In fact in PHP, an expression is defined as anything
that resolves to a value. This includes integer constants such as 654, variables such
as $user, and function calls such as gettype(). The expression (4 + 5), therefore is
an expression that consists of two further expressions and an operator.
NEW
TERM
An expression is any combination of functions, values, and
operators that resolve to a value. As a rule of thumb, if you can use
it as if it were a value, it is an expression.
Now that we have the principles out of the way, it's time to take a tour of PHP4's
more common operators.
The Assignment Operator
You have met the assignment operator each time we have initialized a variable. It
consists of the single character =. The assignment operator takes the value of its
right-hand operand and assigns it to its left-hand operand:
$name ="matt";
The variable $name now contains the string "matt". Interestingly, this construct is
an expression. It might look at first glance that the assignment operator simply
changes the variable $name without producing a value, but in fact, a statement that
uses the assignment operator always resolves to a copy of the value of the right
operand. Thus
print ( $name = "matt" );
prints the string "matt" to the browser in addition to assigning "matt" to $name.
Arithmetic Operators
The arithmetic operators do exactly what you would expect. Table 4.2 lists these
operators. The addition operator adds the right operand to the left operand. The
subtraction operator subtracts the right-hand operand from the left. The division
operator divides the left-hand operand by the right. The multiplication operator
multiplies the left-hand operand by the right. The modulus operator returns the
remainder of the left operand divided by the right.
Table 4.2: Arithmetic Operators
Operator Name Example Example Result
+ Addition 10+3 13
− Subtraction 10− 3 7
/ Division 10/3 3.3333333333333
* Multiplication 10*3 30
% Modulus 10%3 1
The Concatenation Operator
The concatenation operator is a single dot. Treating both operands as strings, it
appends the right-hand operand to the left. So
"hello"." world"
returns
"hello world"
Regardless of the data types of the operands, they are treated as strings, and the
result always is a string.
More Assignment Operators
Although there is really only one assignment operator, PHP4 provides a number of
combination operators that transform the left-hand operand as well as return a
result. As a rule, operators use their operands without changing their values.
Assignment operators break this rule. A combined assignment operator consists of
a standard operator symbol followed by an equals sign. Combination assignment
operators save you the trouble of using two operators yourself. For example,
$x = 4;
$x += 4; // $x now equals 8
is equivalent to
$x = 4;
$x = $x + 4; // $x now equals 8
There is an assignment operator for each of the arithmetic operators and one for the
concatenation operator. Table 4.3 lists some of the most common.
Table 4.3: Some Combined Assignment Operators
Operator Example Equivalent to
+= $x += 5 $x = $x + 5
− = $x − = 5 $x = $x − 5
/= $x /= 5 $x = $x / 5
*= $x *= 5 $x = $x * 5
%= $x%=5 $x = $x % 5
.= $x .= "test" $x = $x" test"
Each of the examples in Table 4.3 transforms the value of $x using the value of the
right-hand operand.
Comparison Operators
Comparison operators perform tests on their operands. They return the boolean
value true if the test is successful, or false otherwise. This type of expression is
useful in control structures, such as if and while statements. You will meet these in
Hour 5.
To test whether the value contained in $x is smaller than 5, for example, you would
use the less than operator:
$x < 5
If $x contained 3, this expression would be equivalent to the value true. If $x
contained 7, the expression would resolve to false.
Table 4.4 lists the comparison operators.
Table 4.4: Comparison Operators
Operator Name Returns
True if
Example Result
== Equivalence Left is
equivalent
to right
$x == 5 false
!= Non-equivalence Left is not
equivalent
to right
$x != 5 true
=== Identical Left is
equivalent
to right and
they are the
same type
$x === 5 false
> Greater Left is than
greater
than right
$x >4 false
>= Greater than or
equal to
Left is
greater
than or
equal to
right
$x >= 4 true
< Less than Left is less
than right
x < 4 false
<= Less than or equal
to
Left is less
than or
equal to
right
$x <= 4 true
These operators are most commonly used with integers or doubles, although the
equivalence operator is also used to compare strings.
Creating More Complex Test Expressions with the Logical Operators
The logical operators test combinations of booleans. The or operator, for example
returns true if either the left or the right operand is true.
true || false
would return true.
The and operator only returns true if both the left and right operands are true.
true && false
would return false. It's unlikely that you would use a logical operator to test boolean
constants, however. It would make more sense to test two or more expressions that
resolve to a boolean. For example,
( $x > 2 ) && ( $x < 15 )
would return true if $x contained a value that is greater than 2 and smaller than 15.
We include the parentheses to make the code easier to read. Table 4.5 lists the
logical operators.
Labels:
Comments,
database,
Design,
Environment,
php,
programmers,
tags
Data Types
Different types of data take up different amounts of memory and may be treated
differently when they are manipulated in a script. Some programming languages
therefore demand that the programmer declare in advance which type of data a
variable will contain. PHP4 is loosely typed, which means that it will calculate data
types as data is assigned to each variable. This is a mixed blessing. On the one hand,
it means that variables can be used flexibly, holding a string at one point and an
integer at another. On the other hand, this can lead to confusion in larger scripts if
you expect a variable to hold one data type when in fact it holds something
completely different.
Table 4.1 shows the six data types available in PHP4.
Table 4.1: Data Types
Type Example Description
Integer 5 A whole
number
Double 3.234 A floating-point
number
String "hello" A collection of
characters
Boolean true One of the
special values
true or false
Object See Hour 8,
"Objects"
Array See Hour 7,
"Arrays"
Of PHP4's six data types, we will leave arrays and objects for Hours 7 and 8.
You can use PHP4's built-in function gettype() to test the type of any variable. If you
place a variable between the parentheses of the function call, gettype() returns a
string representing the relevant type. Listing 4.4 assigns four different data types to
a single variable, testing it with gettype() each time.
Note You can read more about calling functions in Hour 6, "Functions."
Listing 4.4: Testing the Type of a Variable
1: <html>
2: <head>
3: <title>Listing 4.3 Testing the type of a variable</title>
4: </head>
5: <body>
6: <?php
7: $testing = 5;
8: print gettype( $testing ); // integer
9: print "<br>";
10: $testing = "five";
11: print gettype( $testing ); // string
12: print("<br>");
13: $testing = 5.0;
14: print gettype( $testing ); // double
15: print("<br>");
16: $testing = true;
17: print gettype( $testing ); // boolean
18: print "<br>";
19: ?>
20: </body>
21: </html>
This script produces the following:
integer
string
double
boolean
An integer is a whole or real number. In simple terms, it can be said to be a number
without a decimal point. A string is a collection of characters. When you work with
strings in your scripts, they should always be surrounded by double (") or single (')
quotation marks. A double is a floating-point number. That is, a number that
includes a decimal point. A boolean can be one of two special values, true or false.
Note Prior to PHP4, there was no boolean type. Although true was used, it
actually resolved to the integer 1.
Changing Type with settype()
PHP provides the function settype() to change the type of a variable. To use
settype(), you must place the variable to change (and the type to change it to)
between the parentheses and separated by commas. Listing 4.5 converts 3.14 (a
double) to the four types that we are covering in this hour.
Listing 4.5: Changing the Type of a Variable with settype()
1: <html>
2: <head>
3: <title>Listing 4.5 Changing the type of a variable with settype()</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: print gettype( $undecided ); // double
9: print " -- $undecided<br>"; // 3.14
10: settype( $undecided, string );
11: print gettype( $undecided ); // string
12: print " -- $undecided<br>"; // 3.14
13: settype( $undecided, integer );
14: print gettype( $undecided ); // integer
15: print " -- $undecided<br>"; // 3
16: settype( $undecided, double );
17: print gettype( $undecided ); // double
18: print " -- $undecided<br>"; // 3.0
19: settype( $undecided, boolean );
20: print gettype( $undecided ); // boolean
21: print " -- $undecided<br>"; // 1
22: ?>
23: </body>
24: </html>
In each case, we use gettype() to confirm that the type change worked and then
print the value of the variable $undecided to the browser. When we convert the
string "3.14" to an integer, any information beyond the decimal point is lost forever.
That's why $undecided still contains 3 after we have changed it back to a double.
Finally, we convert $undecided to a boolean. Any number other than 0 becomes true
when converted to a boolean. When printing a boolean in PHP, true is represented
as 1 and false as an empty string, so $undecided is printed as 1.
differently when they are manipulated in a script. Some programming languages
therefore demand that the programmer declare in advance which type of data a
variable will contain. PHP4 is loosely typed, which means that it will calculate data
types as data is assigned to each variable. This is a mixed blessing. On the one hand,
it means that variables can be used flexibly, holding a string at one point and an
integer at another. On the other hand, this can lead to confusion in larger scripts if
you expect a variable to hold one data type when in fact it holds something
completely different.
Table 4.1 shows the six data types available in PHP4.
Table 4.1: Data Types
Type Example Description
Integer 5 A whole
number
Double 3.234 A floating-point
number
String "hello" A collection of
characters
Boolean true One of the
special values
true or false
Object See Hour 8,
"Objects"
Array See Hour 7,
"Arrays"
Of PHP4's six data types, we will leave arrays and objects for Hours 7 and 8.
You can use PHP4's built-in function gettype() to test the type of any variable. If you
place a variable between the parentheses of the function call, gettype() returns a
string representing the relevant type. Listing 4.4 assigns four different data types to
a single variable, testing it with gettype() each time.
Note You can read more about calling functions in Hour 6, "Functions."
Listing 4.4: Testing the Type of a Variable
1: <html>
2: <head>
3: <title>Listing 4.3 Testing the type of a variable</title>
4: </head>
5: <body>
6: <?php
7: $testing = 5;
8: print gettype( $testing ); // integer
9: print "<br>";
10: $testing = "five";
11: print gettype( $testing ); // string
12: print("<br>");
13: $testing = 5.0;
14: print gettype( $testing ); // double
15: print("<br>");
16: $testing = true;
17: print gettype( $testing ); // boolean
18: print "<br>";
19: ?>
20: </body>
21: </html>
This script produces the following:
integer
string
double
boolean
An integer is a whole or real number. In simple terms, it can be said to be a number
without a decimal point. A string is a collection of characters. When you work with
strings in your scripts, they should always be surrounded by double (") or single (')
quotation marks. A double is a floating-point number. That is, a number that
includes a decimal point. A boolean can be one of two special values, true or false.
Note Prior to PHP4, there was no boolean type. Although true was used, it
actually resolved to the integer 1.
Changing Type with settype()
PHP provides the function settype() to change the type of a variable. To use
settype(), you must place the variable to change (and the type to change it to)
between the parentheses and separated by commas. Listing 4.5 converts 3.14 (a
double) to the four types that we are covering in this hour.
Listing 4.5: Changing the Type of a Variable with settype()
1: <html>
2: <head>
3: <title>Listing 4.5 Changing the type of a variable with settype()</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: print gettype( $undecided ); // double
9: print " -- $undecided<br>"; // 3.14
10: settype( $undecided, string );
11: print gettype( $undecided ); // string
12: print " -- $undecided<br>"; // 3.14
13: settype( $undecided, integer );
14: print gettype( $undecided ); // integer
15: print " -- $undecided<br>"; // 3
16: settype( $undecided, double );
17: print gettype( $undecided ); // double
18: print " -- $undecided<br>"; // 3.0
19: settype( $undecided, boolean );
20: print gettype( $undecided ); // boolean
21: print " -- $undecided<br>"; // 1
22: ?>
23: </body>
24: </html>
In each case, we use gettype() to confirm that the type change worked and then
print the value of the variable $undecided to the browser. When we convert the
string "3.14" to an integer, any information beyond the decimal point is lost forever.
That's why $undecided still contains 3 after we have changed it back to a double.
Finally, we convert $undecided to a boolean. Any number other than 0 becomes true
when converted to a boolean. When printing a boolean in PHP, true is represented
as 1 and false as an empty string, so $undecided is printed as 1.
Dynamic Variables
As you know, you create a variable with a dollar sign followed by a variable name.
Unusually, the variable name can itself be stored in a variable. So, when assigning
a value to a variable
$user = "bob";
is equivalent to
$holder="user";
$$holder = "bob";
The $holder variable contains the string "user", so you can think of $$holder as a
dollar sign followed by the value of $holder. PHP interprets this as $user.
Note You can use a string constant to define a dynamic variable instead of a
variable. To do so, you must wrap the string you want to use for the variable
name in braces:
${"user"} = "bob";
This might not seem useful at first glance. However, by using the
concatenation operator and a loop (see Hour 5, "Going with the Flow"), you
can use this technique to create tens of variables dynamically.
When accessing a dynamic variable, the syntax is exactly the same:
$user ="bob";
print $user;
is equivalent to
$user ="bob";
$holder="user";
print $$holder;
If you want to print a dynamic variable within a string, however, you need to give
the interpreter some help. The following print statement:
$user="bob";
$holder="user";
print "$$holder";
does not print "bob" to the browser as you might expect. Instead it prints the strings
"$" and "user" together to make "$user". When you place a variable within
quotation marks, PHP helpfully inserts its value. In this case, PHP replaces $holder
with the string "user". The first dollar sign is left in place. To make it clear to PHP
that a variable within a string is part of a dynamic variable, you must wrap it in
braces. The print statement in the following fragment:
$user="bob";
$holder="user";
print "${$holder}";
now prints "bob", which is the value contained in $user.
Listing 4.1 brings some of the previous code fragments together into a single script
using a string stored in a variable to initialize and access a variable called $user.
Listing 4.1: Dynamically Setting and Accessing Variables
1: <html>
2: <head>
3: <title>Listing 4.1 Dynamically setting and accessing variables</title>
4: </head>
5: <body>
6: <?php
7: $holder = "user";
8: $$holder = "bob";
9:
10: // could have been:
11: // $user = "bob";
12: // ${"user"} = "bob";
13:
14: print "$user<br>"; // prints "bob"
15: print $$holder; // prints "bob"
16: print "<br>";
17: print "${$holder}<br>"; // prints "bob"
18: print "${'user'}<br>"; // prints "bob"
19: ?>
20: </body>
21: </html>
References to Variables
By default, variables are assigned by value. In other words, if you were to assign
$aVariable to $anotherVariable, a copy of the value held in $aVariable would be
stored in $anotherVariable. Subsequently changing the value of $aVariable would
have no effect on the contents of $anotherVariable. Listing 4.2 illustrates this.
Listing 4.2: Variables Are Assigned by Value
1: <html>
2: <head>
3: <title>Listing 4.2 Variables are assigned by value</title>
4: </head>
5: <body>
6: <?php
7: $aVariable = 42;
8: $anotherVariable = $aVariable;
9: // a copy of the contents of $aVariable is placed in $anotherVariable
10: $aVariable = 325;
11: print $anotherVariable; // prints 42
12: ?>
13: </body>
14: </html>
This example initializes $aVariable, assigning the value 42 to it. $aVariable is then
assigned to $anotherVariable. A copy of the value of $aVariable is placed in
$anotherVariable. Changing the value of $aVariable to 325 has no effect on the
contents of $anotherVariable. The print statement demonstrates this by outputting
42 to the browser.
In PHP4, you can change this behavior, forcing a reference to $aVariable to be
assigned to $anotherVariable, rather than a copy of its contents. This is illustrated in
Listing 4.3.
Listing 4.3: Assigning a Variable by Reference
1: <html>
2: <head>
3: <title>Listing 4.3 Assigning a variable by reference</title>
4: </head>
5: <body>
6: <?php
7: $aVariable = 42;
8: $anotherVariable = &$aVariable;
9: // a copy of the contents of $aVariable is placed in $anotherVariable
10: $aVariable= 325;
11: print $anotherVariable; // prints 325
12: ?>
13: </body>
14: </html>
We have added only a single character to the code in Listing 4.2. Placing an
ampersand (&) in front of the $aVariable variable ensures that a reference to this
variable, rather than a copy of its contents, is assigned to $anotherVariable. Now
any changes made to $aVariable are seen when accessing $anotherVariable. In
other words, both $aVariable and $anotherVariable now point to the same value.
Because this technique avoids the overhead of copying values from one variable to
another, it can result in a small increase in performance. Unless your script assigns
variables intensively, however, this performance gain will be barely measurable.
Note References to variables were introduced with PHP4.
Unusually, the variable name can itself be stored in a variable. So, when assigning
a value to a variable
$user = "bob";
is equivalent to
$holder="user";
$$holder = "bob";
The $holder variable contains the string "user", so you can think of $$holder as a
dollar sign followed by the value of $holder. PHP interprets this as $user.
Note You can use a string constant to define a dynamic variable instead of a
variable. To do so, you must wrap the string you want to use for the variable
name in braces:
${"user"} = "bob";
This might not seem useful at first glance. However, by using the
concatenation operator and a loop (see Hour 5, "Going with the Flow"), you
can use this technique to create tens of variables dynamically.
When accessing a dynamic variable, the syntax is exactly the same:
$user ="bob";
print $user;
is equivalent to
$user ="bob";
$holder="user";
print $$holder;
If you want to print a dynamic variable within a string, however, you need to give
the interpreter some help. The following print statement:
$user="bob";
$holder="user";
print "$$holder";
does not print "bob" to the browser as you might expect. Instead it prints the strings
"$" and "user" together to make "$user". When you place a variable within
quotation marks, PHP helpfully inserts its value. In this case, PHP replaces $holder
with the string "user". The first dollar sign is left in place. To make it clear to PHP
that a variable within a string is part of a dynamic variable, you must wrap it in
braces. The print statement in the following fragment:
$user="bob";
$holder="user";
print "${$holder}";
now prints "bob", which is the value contained in $user.
Listing 4.1 brings some of the previous code fragments together into a single script
using a string stored in a variable to initialize and access a variable called $user.
Listing 4.1: Dynamically Setting and Accessing Variables
1: <html>
2: <head>
3: <title>Listing 4.1 Dynamically setting and accessing variables</title>
4: </head>
5: <body>
6: <?php
7: $holder = "user";
8: $$holder = "bob";
9:
10: // could have been:
11: // $user = "bob";
12: // ${"user"} = "bob";
13:
14: print "$user<br>"; // prints "bob"
15: print $$holder; // prints "bob"
16: print "<br>";
17: print "${$holder}<br>"; // prints "bob"
18: print "${'user'}<br>"; // prints "bob"
19: ?>
20: </body>
21: </html>
References to Variables
By default, variables are assigned by value. In other words, if you were to assign
$aVariable to $anotherVariable, a copy of the value held in $aVariable would be
stored in $anotherVariable. Subsequently changing the value of $aVariable would
have no effect on the contents of $anotherVariable. Listing 4.2 illustrates this.
Listing 4.2: Variables Are Assigned by Value
1: <html>
2: <head>
3: <title>Listing 4.2 Variables are assigned by value</title>
4: </head>
5: <body>
6: <?php
7: $aVariable = 42;
8: $anotherVariable = $aVariable;
9: // a copy of the contents of $aVariable is placed in $anotherVariable
10: $aVariable = 325;
11: print $anotherVariable; // prints 42
12: ?>
13: </body>
14: </html>
This example initializes $aVariable, assigning the value 42 to it. $aVariable is then
assigned to $anotherVariable. A copy of the value of $aVariable is placed in
$anotherVariable. Changing the value of $aVariable to 325 has no effect on the
contents of $anotherVariable. The print statement demonstrates this by outputting
42 to the browser.
In PHP4, you can change this behavior, forcing a reference to $aVariable to be
assigned to $anotherVariable, rather than a copy of its contents. This is illustrated in
Listing 4.3.
Listing 4.3: Assigning a Variable by Reference
1: <html>
2: <head>
3: <title>Listing 4.3 Assigning a variable by reference</title>
4: </head>
5: <body>
6: <?php
7: $aVariable = 42;
8: $anotherVariable = &$aVariable;
9: // a copy of the contents of $aVariable is placed in $anotherVariable
10: $aVariable= 325;
11: print $anotherVariable; // prints 325
12: ?>
13: </body>
14: </html>
We have added only a single character to the code in Listing 4.2. Placing an
ampersand (&) in front of the $aVariable variable ensures that a reference to this
variable, rather than a copy of its contents, is assigned to $anotherVariable. Now
any changes made to $aVariable are seen when accessing $anotherVariable. In
other words, both $aVariable and $anotherVariable now point to the same value.
Because this technique avoids the overhead of copying values from one variable to
another, it can result in a small increase in performance. Unless your script assigns
variables intensively, however, this performance gain will be barely measurable.
Note References to variables were introduced with PHP4.
The Building Blocks
Overview
In this hour, you are going to get your hands dirty with some of the nuts and bolts
of the language.
There's a lot of ground to cover, and if you are new to programming, you might feel
bombarded with information. Don't worry— you can always refer back here later on.
Concentrate on understanding rather than memorizing the features covered.
If you're already an experienced programmer, you should at least skim this hour's
lesson. It covers a few PHP-specific features.
In this hour, you will learn
About variables— what they are and how to use them
How to define and access variables
About data types
About some of the more commonly used operators
How to use operators to create expressions
How to define and use constants
Variables
A variable is a special container that you can define to "hold" a value. A variable
consists of a name that you can choose, preceded by a dollar ($) sign. The variable
name can include letters, numbers, and the underscore character (_). Variable
names cannot include spaces or characters that are not alphanumeric. The following
code defines some legal variables:
$a;
$a_longish_variable_name;
$2453;
$sleepyZZZZ
Remember that a semicolon (;) is used to end a PHP statement. The semicolons in
the previous fragment of code are not part of the variable names.
NEW
TERM
A variable is a holder for a type of data. It can hold numbers, strings of
characters, objects, arrays, or booleans. The contents of a variable can
be changed at any time.
In this hour, you are going to get your hands dirty with some of the nuts and bolts
of the language.
There's a lot of ground to cover, and if you are new to programming, you might feel
bombarded with information. Don't worry— you can always refer back here later on.
Concentrate on understanding rather than memorizing the features covered.
If you're already an experienced programmer, you should at least skim this hour's
lesson. It covers a few PHP-specific features.
In this hour, you will learn
About variables— what they are and how to use them
How to define and access variables
About data types
About some of the more commonly used operators
How to use operators to create expressions
How to define and use constants
Variables
A variable is a special container that you can define to "hold" a value. A variable
consists of a name that you can choose, preceded by a dollar ($) sign. The variable
name can include letters, numbers, and the underscore character (_). Variable
names cannot include spaces or characters that are not alphanumeric. The following
code defines some legal variables:
$a;
$a_longish_variable_name;
$2453;
$sleepyZZZZ
Remember that a semicolon (;) is used to end a PHP statement. The semicolons in
the previous fragment of code are not part of the variable names.
NEW
TERM
A variable is a holder for a type of data. It can hold numbers, strings of
characters, objects, arrays, or booleans. The contents of a variable can
be changed at any time.
The Print Function
print() is a function that outputs data. In most cases, anything output by print()
ends up in the browser window. A function is a command that performs an action,
usually modified in some way by data provided for it. Data sent to a function is
almost always placed in parentheses after the function name. In this case, you sent
the print() function a collection of characters, or string. Strings must always be
enclosed by quotation marks, either single or double.
Note Function calls generally require parentheses after their name whether or
not they demand that data be passed to them. print() is an exception,
and enclosing the data you want to print to the browser in parentheses is
optional. This is the more common syntax, so we will usually omit the
brackets in our examples.
You ended your only line of code in Listing 3.1 with a semicolon. The semicolon
informs the interpreter that you have completed a statement.
NEW
TERM
A statement represents an instruction to the interpreter. Broadly, it
is to PHP what a sentence is to written or spoken English. A
statement should usually end with a semicolon; a sentence should
end with a period. Exceptions to this include statements that
enclose other statements, and statements that end a block of code.
In most cases, however, failure to end a statement with a semicolon
will confuse the interpreter and result in an error.
Because the statement in Listing 3.1 is the final one in that block of code, the
semicolon is optional.
Combining HTML and PHP
The script in Listing 3.1 is pure PHP. You can incorporate this into an HTML
document simply by adding HTML outside the PHP start and end tags, as shown in
Listing 3.2.
Listing 3.2: A PHP Script Including HTML
1: <html>
2: <head>
3: <title>Listing 3.2 A PHP script including HTML</title>
4: </head>
5: <body>
6: <b>
7: <?php
8: print "hello world";
9: ?>
10: </b>
11: </body>
12: </html>
As you can see, incorporating HTML into a PHP document is simply a matter of
typing in the code. The PHP interpreter ignores everything outside PHP open and
close tags. If you were to view Listing 3.2 with a browser, as shown in Figure 3.4,
you would see the string "hello world" in bold. If you were to view the document
source, as shown in Figure 3.5, the listing would look exactly like a normal HTML
document.
You can include as many blocks of PHP code as you need in a single document,
interspersing them with HTML as required. Although you can have multiple blocks of
code in a single document, they combine to form a single script. Anything defined in
the first block (variables, functions, or classes, for example) usually will be available
to subsequent blocks.
Figure 3.4: The output of Listing 3.2 as viewed in a browser.
Figure 3.5: The output of Listing 3.2 as HTML source code.
Adding Comments to PHP Code
Code that seems clear at the time of writing, can seem like a hopeless tangle when
you come to amend it six months later. Adding comments to your code as you write
can save you time later on and make it easier for other programmers to work with
your code.
NEW
TERM
A comment is text in a script that is ignored by the interpreter.
Comments can be used to make code more readable, or to annotate a
script.
Single line comments begin with two forward slashes (/ /) or a single hash sign (#).
All text from either of these marks until either the end of the line or the PHP close tag
is ignored.
// this is a comment
# this is another comment
Multiline comments begin with a forward slash followed by an asterisk (/*) and end
with an asterisk followed by a forward slash (*/).
/*
this is a comment
none of this will
be parsed by the
interpreter
*/
ends up in the browser window. A function is a command that performs an action,
usually modified in some way by data provided for it. Data sent to a function is
almost always placed in parentheses after the function name. In this case, you sent
the print() function a collection of characters, or string. Strings must always be
enclosed by quotation marks, either single or double.
Note Function calls generally require parentheses after their name whether or
not they demand that data be passed to them. print() is an exception,
and enclosing the data you want to print to the browser in parentheses is
optional. This is the more common syntax, so we will usually omit the
brackets in our examples.
You ended your only line of code in Listing 3.1 with a semicolon. The semicolon
informs the interpreter that you have completed a statement.
NEW
TERM
A statement represents an instruction to the interpreter. Broadly, it
is to PHP what a sentence is to written or spoken English. A
statement should usually end with a semicolon; a sentence should
end with a period. Exceptions to this include statements that
enclose other statements, and statements that end a block of code.
In most cases, however, failure to end a statement with a semicolon
will confuse the interpreter and result in an error.
Because the statement in Listing 3.1 is the final one in that block of code, the
semicolon is optional.
Combining HTML and PHP
The script in Listing 3.1 is pure PHP. You can incorporate this into an HTML
document simply by adding HTML outside the PHP start and end tags, as shown in
Listing 3.2.
Listing 3.2: A PHP Script Including HTML
1: <html>
2: <head>
3: <title>Listing 3.2 A PHP script including HTML</title>
4: </head>
5: <body>
6: <b>
7: <?php
8: print "hello world";
9: ?>
10: </b>
11: </body>
12: </html>
As you can see, incorporating HTML into a PHP document is simply a matter of
typing in the code. The PHP interpreter ignores everything outside PHP open and
close tags. If you were to view Listing 3.2 with a browser, as shown in Figure 3.4,
you would see the string "hello world" in bold. If you were to view the document
source, as shown in Figure 3.5, the listing would look exactly like a normal HTML
document.
You can include as many blocks of PHP code as you need in a single document,
interspersing them with HTML as required. Although you can have multiple blocks of
code in a single document, they combine to form a single script. Anything defined in
the first block (variables, functions, or classes, for example) usually will be available
to subsequent blocks.
Figure 3.4: The output of Listing 3.2 as viewed in a browser.
Figure 3.5: The output of Listing 3.2 as HTML source code.
Adding Comments to PHP Code
Code that seems clear at the time of writing, can seem like a hopeless tangle when
you come to amend it six months later. Adding comments to your code as you write
can save you time later on and make it easier for other programmers to work with
your code.
NEW
TERM
A comment is text in a script that is ignored by the interpreter.
Comments can be used to make code more readable, or to annotate a
script.
Single line comments begin with two forward slashes (/ /) or a single hash sign (#).
All text from either of these marks until either the end of the line or the PHP close tag
is ignored.
// this is a comment
# this is another comment
Multiline comments begin with a forward slash followed by an asterisk (/*) and end
with an asterisk followed by a forward slash (*/).
/*
this is a comment
none of this will
be parsed by the
interpreter
*/
Sunday, 5 July 2015
A First Script php
Overview
Having installed and configured PHP, it is now time to put it to the test. In this hour,you will create your first script and spend a little time analyzing its syntax. By the
end of the hour, you should be ready to create documents that include both HTML
and PHP.
In this hour, you will learn
How to create, upload, and run a PHP script
How to incorporate HTML and PHP in the same document
How to make your code clearer with comments
Our First Script
Let's jump straight in with a PHP script. To begin, open your favorite text editor. LikeHTML documents, PHP files are made up of plain text. You can create them with any
text editor, such as Notepad on Windows, Simple Text and BBEdit on MacOS, or VI
and Emacs on UNIX operating systems. Most popular HTML editors provide at least
some support for PHP.
Type in the example in Listing 3.1 and save the file, calling it something like
first.php.
Listing 3.1: A First PHP Script
1: <?php2: print "Hello Web!";
3: ?>
Figure 3.1 shows the script created in Listing 3.1 as typed into the BBEdit text editor
for MacOS.
Figure 3.1: Your first script as created in the BBEdit text editor.
The extension to the PHP document is important because it tells the server to treat
the file as PHP code and invoke the interpreter. The default PHP extension for a PHP
4 document is .php. This can be changed, however, by altering the server's
configuration. You saw how to do this in Hour 2, "Installing PHP."
If you are not working directly on the machine that will be serving your PHP script,
you will probably need to use an FTP client, such as WS-FTP for Windows or Fetch for
MacOS to upload your saved document to the server.
After the document is in place, you should be able to access it via your browser. If
all has gone well, you should see the script's output. Figure 3.2 shows the output
from the first.php script.
Figure 3.2: Success: the output from Listing 3.1.
If PHP is not installed on your server or your file's extension is not recognized, youmay not see the output shown in Figure 3.2. In these cases, you probably will see
the source code created in Listing 3.1. Figure 3.3 shows what happens when an
unknown extension is encountered.
Figure 3.3: Failure: the extension is not recognized.
If this happens, first check the extension with which you saved your PHP script. In
Figure 3.3, the document was accidentally called first.nphp. If the file extension is
as it should be, you may need to check that PHP has been installed properly and that
your server is configured to work with the extension that you have used for your
script. You can read more about installing and configuring PHP in Hour 2.
Now that you have uploaded and tested your script, you can take a look at the code
in a little more detail.
Beginning and Ending a Block of PHP Statements
When writing PHP, you need to inform the interpreter that you want it to execute
your commands. If you don't do this, the code you write will be mistaken for HTML
and will be output to the browser. Table 3.1 shows the four ways of enclosing PHP
code.
Table 3.1: PHP Start and End Tags
Tag Style Start Tag End Tag
Standard
tags
<?php ?>
Short tags <? ?>
ASP tags <% %>
Script tags <SCRIPT
LANGUAGE="php"
>
</SCRIPT>
Of the tags in Table 3.1, only the standard and the script tags can be guaranteed to
work on any configuration. The short and ASP style tags must be explicitly enabled
in your php.ini. You examined the php.ini file in Hour 2.
To activate recognition for short tags, you must make sure that the short_open_tag
switch is set to "On" in php.ini:
short_open_tag = On;
Short tags are enabled by default, so you would only need to edit php.ini if you want
to disable these.
To activate recognition for the ASP style tags, you must enable the asp_tags
setting:
asp_tags = On;
After you have edited php.ini, you should be able to choose from any of the four
styles for use in your scripts. This is largely a matter of preference, although if you
intend to work with XML, you should disable the short tags (<? ?>) and work with
the standard tags (<?php ?>).
Let's run through some of the ways in which you can legally write the code in Listing
3.1. You could use any of the four PHP start and end tags that you have seen:
<?
print("Hello Web!");
?>
<?php
print("Hello Web!");
?>
<%
print("Hello Web!");
%>
<SCRIPT LANGUAGE="php">
print("Hello Web!");
</SCRIPT>
Single lines of code in PHP also can be presented on the same line as the PHP start
and end tags:
<? print("Hello Web!"); ?>
Now that you know how to define a block of PHP code, take a closer look at the code
in Listing 3.1 itself.
Workshop
Q&A
Q You have covered an installation for Linux and Apache. Does that mean
that this book will not apply to my server and operating system?
A No, one of PHP's great strengths is that it runs on multiple platforms. If you are
having trouble installing PHP to work on your operating system or with your server,
don't forget to read the files that come with your PHP distribution. You should find
comprehensive step-by-step instructions for installation. If you are still having
problems, review the "Help!" section earlier in this hour. The online resources
mentioned there will almost certainly contain the answers you need.
Workshop
The Workshop provides quiz questions to help you solidify your understanding of the
material covered. Try to understand the quiz answers before continuing to the next
hour's lesson. Quiz answers are provided in Appendix A.
Quiz
Where can you find the PHP online manual?
From a UNIX operating system, how would you get help on configuration options
(the options that you pass to the configure script in your PHP distribution)?
Q You have covered an installation for Linux and Apache. Does that mean
that this book will not apply to my server and operating system?
A No, one of PHP's great strengths is that it runs on multiple platforms. If you are
having trouble installing PHP to work on your operating system or with your server,
don't forget to read the files that come with your PHP distribution. You should find
comprehensive step-by-step instructions for installation. If you are still having
problems, review the "Help!" section earlier in this hour. The online resources
mentioned there will almost certainly contain the answers you need.
Workshop
The Workshop provides quiz questions to help you solidify your understanding of the
material covered. Try to understand the quiz answers before continuing to the next
hour's lesson. Quiz answers are provided in Appendix A.
Quiz
Where can you find the PHP online manual?
From a UNIX operating system, how would you get help on configuration options
(the options that you pass to the configure script in your PHP distribution)?
Configuring Apache
After you have compiled PHP and Apache, you should check Apache's configuration
file, httpd.conf, which you will find in a directory called conf in the Apache install
directory. Add the following lines to this file:
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
This ensures that the PHP interpreter will parse files that end with the .php
extension. Any files with the .phps extension will be output as PHP source. That is,
the source code will be converted to HTML and color-coded. This can be useful for
debugging your scripts.
If you want to offer to your users PHP pages with extensions more familiar to them,
you can choose any extension you want. You can even ensure that files with
the .html extension are treated as PHP files with the following:
AddType application/x-httpd-php .html
Note that treating files with the .html extension as PHP scripts could slow down your
site, because every page with this extension will be parsed by the PHP interpreter
before it is served to the user.
If PHP has been preinstalled and you have no access to the Apache configuration
files, you may be able to change the extensions that will determine which files will
be treated as PHP executables by including an AddType directive in a file
called .htaccess. After you have created this file, the directive will affect the
enclosing directory, as well as any subdirectories. This technique will only work if
the AllowOverride directive for the enclosing directory is set to either FileInfo or All.
Although the filename .htaccess is the default for an access control file, it may have
been changed. Check the AccessFileName directive in httpd.conf to find out. Even if
you don't have root access, you should be able to read the Apache configuration
files.
An .htaccess file can be an excellent way of customizing your server space if you do
not have access to the root account. An additional way of controlling the behavior of
PHP, even as a non-root user, is the php.ini file.
php.ini
After you have compiled or installed PHP, you can still change its behavior with a file
called php.ini. On UNIX systems, the default location for this file is /usr/local/lib;
on a Windows system, the default location is the Windows directory. A php.ini file
in the current working directory will override one in the default location, so you can
change the behavior of PHP on a per-directory basis.
You should find a sample php.ini file in your distribution directory, which contains
factory settings. Factory settings will be used if no php.ini file is used.
The default settings should be adequate for most of the examples in this book,
although you can read about some amendments you might like to make in Hour 22,
"Debugging."
Directives in the php.ini file take the form of a directive and a value separated by an
equals sign. Whitespace is ignored.
If PHP has been preinstalled on your system, you might want to check some of the
settings in php.ini. Remember, if you are not allowed to alter this document, you
can create one in your script's directory that can override the default. You can also
set an environmental variable PHPRC that designates a php.ini file.
You can change your php.ini settings at any time, though if you are running PHP as
an Apache module, you should restart the server for the changes to take effect.
short_open_tag
The short_open_tag directive determines whether you can begin a block of PHP
code with the symbols <? and close it with ?>. If this has been disabled, you will see
one of the following:
short_open_tag = Off
short_open_tag = False
short_open_tag = No
To enable the directive you can use one of the following:
short_open_tag = On
short_open_tag = True
short_open_tag = Yes
You can read more about PHP open and close tags in Hour 3, "A First Script."
Error Reporting Directives
To diagnose bugs in your code, you should enable the directive that allows error
messages to be written to the browser. This is on by default:
display_errors = On
You can also set the level of error reporting. We will cover the options available for
the error_reporting directive in more depth in Hour 22. For now, however, you
should set this to the following:
error_reporting = E_ALL & ~ E_NOTICE
This will report all errors but not notices that warn about potential problems with
your code. Notices can interfere with some PHP techniques. This setting is the
default.
Variable Directives
PHP makes certain variables available to you as a result of a GET request, a POST
request, or a cookie. You can influence this in the php.ini file.
The track_vars directive creates associative arrays containing elements generated
as a result of an HTTP request. This is allowed by default:
track_vars = On
The register_globals directive determines whether values resulting from an HTTP
request should be made available as global variables. Many scripts in this book will
require the following setting to be enabled:
register_globals = On
Help!
Help is always at hand on the Internet, particularly for problems concerning open
source software. Wait a moment before you hit the send button, however. No
matter how intractable your installation, configuration, or programming problem
might seem, chances are you are not alone. Someone will have already answered
your question.
When you hit a brick wall, your first recourse should be to the official PHP site at
<http://www.php.net/>, particularly the annotated manual at
<http://www.php.net/manual>.
If you still can't find your answer, don't forget that the PHP site is searchable. The
advice you are seeking may be lurking in a press release or a Frequently Asked
Questions file. Another excellent and searchable resource is the PHP Knowledge
Base at <http://www.faqts.com/knowledge-base/index.phtml>.
Still no luck? You can find links to searchable mailing list archives at
<http://www.php.net/mailsearch.php3>. These archives represent a huge
information resource with contributions from many of the great and the good in the
PHP community. Spend some time trying out a few keyword combinations.
If you are still convinced that your problem has not been addressed, you may well
be doing the PHP community a service by exposing it.
You can join the PHP mailing lists at <http://www.php.net/support.php3>.
Although these lists are often high volume, you can learn a lot from them. If you are
serious about PHP scripting, you should certainly subscribe at least to a digest list.
Once subscribed to the list that matches your concerns, you might consider posting
your problem.
When you post a question it is often a good idea to include as much information as
possible (without writing a novel). The following items often are pertinent:
Your operating system
The version of PHP you are running or installing
The configure options you chose
Any output from the configure or make commands that preceded an installation
failure
A reasonably complete example of the code that is causing you problems
Why all these cautions about posting a question to a mailing list? First, developing
research skills will stand you in good stead. A good researcher can generally solve a
problem quickly and efficiently. Asking a naive question of a technical list often
involves a wait rewarded only by a message or two referring you to the archives
where you should have begun your search for answers.
Second, remember that a mailing list is not analogous to a technical support call
center. No one is paid to answer your questions. Despite this, you have access to an
impressive resource of talent and knowledge, including that of some of the creators
of PHP itself. A good question and its answer will be archived to help other coders.
Asking a question that has been answered several times just adds more noise.
Having said this, don't be afraid to post a problem to the list. PHP developers are a
civilized and helpful breed, and by bringing a problem to the attention of the
community, you might be helping others to solve the same problem.
that you use a particular server, operating system, or database.
In this hour, you learned where to locate PHP and other open source software that
can help you host and serve Web sites. You learned how to compile PHP as an
Apache module on Linux. If you download a PHP binary for another platform, your
distribution will contain step-by-step instructions. You learned some of the
configure options that can change the features that your binary will support. You
learned about php.ini and some of the directive it contains. Finally, you learned
about sources of support. You should now be ready to come to grips with the
language itself.
file, httpd.conf, which you will find in a directory called conf in the Apache install
directory. Add the following lines to this file:
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
This ensures that the PHP interpreter will parse files that end with the .php
extension. Any files with the .phps extension will be output as PHP source. That is,
the source code will be converted to HTML and color-coded. This can be useful for
debugging your scripts.
If you want to offer to your users PHP pages with extensions more familiar to them,
you can choose any extension you want. You can even ensure that files with
the .html extension are treated as PHP files with the following:
AddType application/x-httpd-php .html
Note that treating files with the .html extension as PHP scripts could slow down your
site, because every page with this extension will be parsed by the PHP interpreter
before it is served to the user.
If PHP has been preinstalled and you have no access to the Apache configuration
files, you may be able to change the extensions that will determine which files will
be treated as PHP executables by including an AddType directive in a file
called .htaccess. After you have created this file, the directive will affect the
enclosing directory, as well as any subdirectories. This technique will only work if
the AllowOverride directive for the enclosing directory is set to either FileInfo or All.
Although the filename .htaccess is the default for an access control file, it may have
been changed. Check the AccessFileName directive in httpd.conf to find out. Even if
you don't have root access, you should be able to read the Apache configuration
files.
An .htaccess file can be an excellent way of customizing your server space if you do
not have access to the root account. An additional way of controlling the behavior of
PHP, even as a non-root user, is the php.ini file.
php.ini
After you have compiled or installed PHP, you can still change its behavior with a file
called php.ini. On UNIX systems, the default location for this file is /usr/local/lib;
on a Windows system, the default location is the Windows directory. A php.ini file
in the current working directory will override one in the default location, so you can
change the behavior of PHP on a per-directory basis.
You should find a sample php.ini file in your distribution directory, which contains
factory settings. Factory settings will be used if no php.ini file is used.
The default settings should be adequate for most of the examples in this book,
although you can read about some amendments you might like to make in Hour 22,
"Debugging."
Directives in the php.ini file take the form of a directive and a value separated by an
equals sign. Whitespace is ignored.
If PHP has been preinstalled on your system, you might want to check some of the
settings in php.ini. Remember, if you are not allowed to alter this document, you
can create one in your script's directory that can override the default. You can also
set an environmental variable PHPRC that designates a php.ini file.
You can change your php.ini settings at any time, though if you are running PHP as
an Apache module, you should restart the server for the changes to take effect.
short_open_tag
The short_open_tag directive determines whether you can begin a block of PHP
code with the symbols <? and close it with ?>. If this has been disabled, you will see
one of the following:
short_open_tag = Off
short_open_tag = False
short_open_tag = No
To enable the directive you can use one of the following:
short_open_tag = On
short_open_tag = True
short_open_tag = Yes
You can read more about PHP open and close tags in Hour 3, "A First Script."
Error Reporting Directives
To diagnose bugs in your code, you should enable the directive that allows error
messages to be written to the browser. This is on by default:
display_errors = On
You can also set the level of error reporting. We will cover the options available for
the error_reporting directive in more depth in Hour 22. For now, however, you
should set this to the following:
error_reporting = E_ALL & ~ E_NOTICE
This will report all errors but not notices that warn about potential problems with
your code. Notices can interfere with some PHP techniques. This setting is the
default.
Variable Directives
PHP makes certain variables available to you as a result of a GET request, a POST
request, or a cookie. You can influence this in the php.ini file.
The track_vars directive creates associative arrays containing elements generated
as a result of an HTTP request. This is allowed by default:
track_vars = On
The register_globals directive determines whether values resulting from an HTTP
request should be made available as global variables. Many scripts in this book will
require the following setting to be enabled:
register_globals = On
Help!
Help is always at hand on the Internet, particularly for problems concerning open
source software. Wait a moment before you hit the send button, however. No
matter how intractable your installation, configuration, or programming problem
might seem, chances are you are not alone. Someone will have already answered
your question.
When you hit a brick wall, your first recourse should be to the official PHP site at
<http://www.php.net/>, particularly the annotated manual at
<http://www.php.net/manual>.
If you still can't find your answer, don't forget that the PHP site is searchable. The
advice you are seeking may be lurking in a press release or a Frequently Asked
Questions file. Another excellent and searchable resource is the PHP Knowledge
Base at <http://www.faqts.com/knowledge-base/index.phtml>.
Still no luck? You can find links to searchable mailing list archives at
<http://www.php.net/mailsearch.php3>. These archives represent a huge
information resource with contributions from many of the great and the good in the
PHP community. Spend some time trying out a few keyword combinations.
If you are still convinced that your problem has not been addressed, you may well
be doing the PHP community a service by exposing it.
You can join the PHP mailing lists at <http://www.php.net/support.php3>.
Although these lists are often high volume, you can learn a lot from them. If you are
serious about PHP scripting, you should certainly subscribe at least to a digest list.
Once subscribed to the list that matches your concerns, you might consider posting
your problem.
When you post a question it is often a good idea to include as much information as
possible (without writing a novel). The following items often are pertinent:
Your operating system
The version of PHP you are running or installing
The configure options you chose
Any output from the configure or make commands that preceded an installation
failure
A reasonably complete example of the code that is causing you problems
Why all these cautions about posting a question to a mailing list? First, developing
research skills will stand you in good stead. A good researcher can generally solve a
problem quickly and efficiently. Asking a naive question of a technical list often
involves a wait rewarded only by a message or two referring you to the archives
where you should have begun your search for answers.
Second, remember that a mailing list is not analogous to a technical support call
center. No one is paid to answer your questions. Despite this, you have access to an
impressive resource of talent and knowledge, including that of some of the creators
of PHP itself. A good question and its answer will be archived to help other coders.
Asking a question that has been answered several times just adds more noise.
Having said this, don't be afraid to post a problem to the list. PHP developers are a
civilized and helpful breed, and by bringing a problem to the attention of the
community, you might be helping others to solve the same problem.
Summary
PHP4 is open source software. It is also open in the sense that it does not demandthat you use a particular server, operating system, or database.
In this hour, you learned where to locate PHP and other open source software that
can help you host and serve Web sites. You learned how to compile PHP as an
Apache module on Linux. If you download a PHP binary for another platform, your
distribution will contain step-by-step instructions. You learned some of the
configure options that can change the features that your binary will support. You
learned about php.ini and some of the directive it contains. Finally, you learned
about sources of support. You should now be ready to come to grips with the
language itself.
Installing PHP4 for Linux and Apache
In this section, we will look at one way of installing PHP4 with Apache on Linux. The
process is more or less the same for any UNIX operating system. You might be able
to find prebuilt versions of PHP for your system, which are simple to install.
Compiling PHP, though, gives you greater control over the features built in to your
binary.
Before you install you should make sure that you are logged into your system as the
root user. If you are not allowed access to your system's root account, you may
need to ask your system administrator to install PHP for you.
There are two ways of compiling an Apache PHP module. You can either recompile
Apache, statically linking PHP into it, or you can compile PHP as a Dynamic Shared
Object (DSO). If your version of Apache was compiled with DSO support, it will be
capable of supporting new modules without the need for recompiling the server.
This method is the easiest way to get PHP up and running, and it is the one we will
look at in this section.
In order to test that Apache supports DSOs you should launch the Apache binary
(httpd) with the -l argument.
/www/bin/httpd -l
You should see a list of modules. If you see
mod_so.c
among them, you should be able to proceed; otherwise, you may need to recompile
Apache. The Apache distribution contains full instructions for this.
If you have not already done so, you will need to download the latest distribution of
PHP4. Your distribution will be archived as a tar file and compressed with gzip, so
you will need to unpack it:
tar -xvzf php-4.0.tar.gz
After your distribution is unpacked, you should move to the PHP4 distribution
directory:
cd ../php-4.0
Within your distribution directory you will find a script called configure. This accepts
arguments that will control the features that PHP will support. For this example, we
will include some useful command line arguments, although you might want to
specify arguments of your own. We will discuss some of the configure options
available to you later in the hour.
./configure --enable-track-vars \
--with-gd \
--with-mysql \
--with-apxs=/www/bin/apxs
The path you assign to the --with-apxs argument is likely to be different on your
system. It is possible that you will find apxs in the same directory as your Apache
executable.
After the configure script has run, you can run the make program. You will need a C
compiler on your system to run this command successfully.
make
make install
These commands should end the process of PHP4 compilation and installation. You
should now be able to configure and run Apache.
Some configure Options
When we ran the configure script, we included some command-line arguments
that determined the features that the PHP interpreter will include. The configure
script itself gives you a list of available options. From the PHP distribution directory
type the following:
./configure --help
The list produced is long, so you may want to add it to a file for reading at leisure:
./configure --help > configoptions.txt
Although the output from this command is very descriptive, we will look at a few
useful options— especially those that might be needed to follow this book.
--enable-track-vars
This option automatically populates associative arrays with values submitted as part
of GET, POST requests or provided in a cookie. You can read more about arrays in
Hour 7, "Arrays," and about HTTP requests in Hour 13, "Beyond the Box." It is a
good idea to include this option when running configure.
--with-gd
--with-gd enables support for the GD library, which, if installed on your system,
allows you to create dynamic GIF or PNG images from your scripts. You can read
more about creating dynamic images in Hour 14, "Working with Dynamic Images."
You can optionally specify a path to your GD library's install directory:
--with-gd=/path/to/dir
--with-mysql
--with-mysql enables support for the MySQL database. If your system has MySQL
installed in a directory other than the default location, you should specify a path:
--with-mysql=/path/to/dir
As you know, PHP provides support for other databases. Table 2.1 lists some of
them and the configure options you will need to use them.
Table 2.1: Some Database configure Options
Database configure Option
Adabas D --with-adabas
FilePro --with-filepro
msql --with-msql
informix --with-informix
iODBC --with-iodbc
OpenLink
ODBC
--with-openlink
Oracle --with-oracle
PostgreSQL --with-pgsql
Solid --with-solid
Sybase --with-sybase
Sybase-CT --with-sybase-ct
Velocis --with-velocis
LDAP --with-ldap
Configuring Apache
After you have compiled PHP and Apache, you should check Apache's configuration
file, httpd.conf, which you will find in a directory called conf in the Apache install
directory. Add the following lines to this file:
Installing PHP
Overview
Before getting started with the PHP language, you must first acquire, install, andconfigure the PHP interpreter. PHP is available for a wide range of platforms and
works in conjunction with many servers.
In this hour, you will learn
Which platforms, servers, and databases are supported by PHP4
Where to find PHP and other useful open source software
One way of installing PHP on Linux
Some options that add features to your PHP binary
Some configuration directives
How to find help when things go wrong
Platforms, Servers, Databases, and PHP
PHP is truly cross-platform. It runs on the Windows operating system, most versionsof UNIX including Linux, and even the Macintosh. Support is provided for a range of
Web servers including Apache (itself open source and cross-platform), Microsoft
Internet Information Server, WebSite Pro, the iPlanet Web Server, and Microsoft's
Personal Web Server. The latter is useful if you want to test your scripts offline on a
Windows machine, although Apache can also be run on Windows.
You can also compile PHP as a standalone application. You can then call it from the
command line. In this book, we will concentrate on building Web applications, but
do not underestimate the power of PHP4 as a general scripting tool comparable to
Perl.
PHP is designed to integrate easily with databases. This feature is one of the factors
that make the language such a good choice for building sophisticated Web
applications. Many databases are directly supported, including Adabas D, InterBase,
Solid, dBASE, mSQL, Sybase, Empress, MySQL, Velocis, FilePro, Oracle, UNIX dbm,
Informix, and PostgreSQL. PHP also supports ODBC.
Throughout this book, we will be using a combination of Linux, Apache, and MySQL.
All these are free to download and use, and can be installed relatively easily on a PC.
You can find out more about getting Linux for your computer at
<http://www.linux.org/help/beginner/distributions.html>. If you want to run Linux
on a Power PC, you can find information about LinuxPPC at
<http://www.linuxppc.org>.
MySQL, the database we will use in this book, can be downloaded from
<http://www.mysql.com>. There are versions for many operating systems
including UNIX, Windows, and OS/2.
On the other hand, you can easily stick with Windows, NT, or MacOS. PHP is, after
all, a cross-platform scripting language.
Where to Find PHP and More
You can find PHP4 at <http://www.php.net/>. PHP4 is open source software, whichmeans that you won't need your credit card handy when you download it.
The PHP WebSite is an excellent resource for PHP coders. The entire manual can be
read online at <http://www.php.net/manual/>, complete with helpful annotations
from other PHP coders. You can also download the manual in several formats.
Saturday, 4 July 2015
Is PHP an easy language to learn
A In short, yes! You really can learn the basics of PHP in 24 hours. PHP provides an
enormous wealth of functions that allow you to do things for which you would have
to write custom code in other languages. PHP also handles data types and memory
issues for you (much like Perl).
Understanding the syntax and structures of a programming language is only the
beginning of the journey, however. Ultimately, you will only really learn by building
your own projects and by making mistakes. You should see this book as a starting
point.
material covered. Try to understand the quiz answers before continuing to the next
hour's lesson. Quiz answers are provided in Appendix A.
What did the initials PHP originally stand for?
enormous wealth of functions that allow you to do things for which you would have
to write custom code in other languages. PHP also handles data types and memory
issues for you (much like Perl).
Understanding the syntax and structures of a programming language is only the
beginning of the journey, however. Ultimately, you will only really learn by building
your own projects and by making mistakes. You should see this book as a starting
point.
Workshop
The Workshop provides quiz questions to help you solidify your understanding of thematerial covered. Try to understand the quiz answers before continuing to the next
hour's lesson. Quiz answers are provided in Appendix A.
Quiz
What did the initials PHP originally stand for?
Who created the original version of PHP?
What is the name of the new scripting engine that powers PHP?
Name a new feature introduced with PHP4.
PHP Is Open Source
To many people, "open source" simply means free, which is, of course, a benefit in
itself. To quote from the official PHP site at http://www.php.net/:
This may sound a little foreign to all you folks coming from a non-UNIX
background, but PHP doesn't cost anything. You can use it for commercial and/or
non-commercial use all you want. You can give it to your friends, print it out and
hang it on your wall or eat it for lunch. Welcome to the world of Open Source
software! Smile, be happy, the world is good. For the full legalese, see the official
license.
Well-maintained open source projects offer users additional benefits, though. You
benefit from an accessible and committed community who offer a wealth of
experience in the subject. Chances are that any problem you encounter in your
coding can be answered swiftly and easily with a little research. If that fails, a
question sent to a mailing list can yield an intelligent, authoritative response.
You also can be sure that bugs will be addressed as they are found, and that new
features will be made available as the need is defined. You will not have to wait for
the next commercial release before taking advantage of improvements.
There is no vested interest in a particular server product or operating system. You
are free to make choices that suit your needs or those of your clients, secure that
your code will run whatever you decide.
tests, beating it in some tests. Compiled PHP leaves ASP far behind.
servers and databases. You can build for a UNIX environment and shift your work to
NT without a problem. You can test a project with Personal Web Server and install it
on a UNIX system running on PHP as an Apache module.
macros to the powerful scripting environment it has become. You found out about
PHP4 and the Zend scripting engine, and how they incorporate new features and
more efficiency. Finally, you discovered some of the features that make PHP a
compelling choice as a Web programming language.
itself. To quote from the official PHP site at http://www.php.net/:
This may sound a little foreign to all you folks coming from a non-UNIX
background, but PHP doesn't cost anything. You can use it for commercial and/or
non-commercial use all you want. You can give it to your friends, print it out and
hang it on your wall or eat it for lunch. Welcome to the world of Open Source
software! Smile, be happy, the world is good. For the full legalese, see the official
license.
Well-maintained open source projects offer users additional benefits, though. You
benefit from an accessible and committed community who offer a wealth of
experience in the subject. Chances are that any problem you encounter in your
coding can be answered swiftly and easily with a little research. If that fails, a
question sent to a mailing list can yield an intelligent, authoritative response.
You also can be sure that bugs will be addressed as they are found, and that new
features will be made available as the need is defined. You will not have to wait for
the next commercial release before taking advantage of improvements.
There is no vested interest in a particular server product or operating system. You
are free to make choices that suit your needs or those of your clients, secure that
your code will run whatever you decide.
Performance
Because of the powerful Zend engine, PHP4 compares well with ASP in benchmarktests, beating it in some tests. Compiled PHP leaves ASP far behind.
Portability
PHP is designed to run on many operating systems and to cooperate with manyservers and databases. You can build for a UNIX environment and shift your work to
NT without a problem. You can test a project with Personal Web Server and install it
on a UNIX system running on PHP as an Apache module.
Summary
In this hour, we introduced PHP. You learned the history of PHP from a simple set ofmacros to the powerful scripting environment it has become. You found out about
PHP4 and the Zend scripting engine, and how they incorporate new features and
more efficiency. Finally, you discovered some of the features that make PHP a
compelling choice as a Web programming language.
The Zend Engine
When PHP3 was written, an entirely new parser was created from the ground up.
PHP4 represents a similar change to the scripting engine. This rewrite, though, is
more significant by orders of magnitude.
Zend is a scripting engine that sits below the PHP-specific modules. It is optimized
to significantly improve performance.
These changes in efficiency will ensure PHP4's continued success. Most code written
for PHP3 will continue to run with no changes; however, these scripts may run up to
200 times faster!
A commercial addition to the Zend engine will be the facility for compiling PHP
scripts. This will provide a further gain in performance that should leave most, if not
all, competitors far behind.
Zend is built to improve performance but is also designed for increased flexibility.
Communication with servers has been improved, so it will be possible to create PHP
modules that work with a wider range of servers. Unlike a CGI interpreter, which sits
outside a server and is initialized every time a script is run, a server module runs in
conjunction with the server. This improves performance because the scripting
engine does not need to be started for a PHP page to be executed.
find that the production process is significantly faster than you might expect if you
are used to working with other scripting languages. As an open source product,
PHP4 is well supported by a talented production team and a committed user
community. Furthermore, PHP can be run on all the major operating systems with
most servers.
notice a significant decrease in development time on many projects. In many
instances, you will be able to separate the coding stage of a project from the design
and build stages. Not only can this make life easier for you as a programmer, it also
can remove obstacles that stand in the way of effective and flexible design.
PHP4 represents a similar change to the scripting engine. This rewrite, though, is
more significant by orders of magnitude.
Zend is a scripting engine that sits below the PHP-specific modules. It is optimized
to significantly improve performance.
These changes in efficiency will ensure PHP4's continued success. Most code written
for PHP3 will continue to run with no changes; however, these scripts may run up to
200 times faster!
A commercial addition to the Zend engine will be the facility for compiling PHP
scripts. This will provide a further gain in performance that should leave most, if not
all, competitors far behind.
Zend is built to improve performance but is also designed for increased flexibility.
Communication with servers has been improved, so it will be possible to create PHP
modules that work with a wider range of servers. Unlike a CGI interpreter, which sits
outside a server and is initialized every time a script is run, a server module runs in
conjunction with the server. This improves performance because the scripting
engine does not need to be started for a PHP page to be executed.
Why Choose PHP?
There are some compelling reasons to work with PHP4. For many projects you willfind that the production process is significantly faster than you might expect if you
are used to working with other scripting languages. As an open source product,
PHP4 is well supported by a talented production team and a committed user
community. Furthermore, PHP can be run on all the major operating systems with
most servers.
Speed of Development
Because PHP allows you to separate HTML code from scripted elements, you willnotice a significant decrease in development time on many projects. In many
instances, you will be able to separate the coding stage of a project from the design
and build stages. Not only can this make life easier for you as a programmer, it also
can remove obstacles that stand in the way of effective and flexible design.
PHP: From Home Page to Portal
Overview
Welcome to PHP! Throughout this book you will look at almost every element of thePHP language. But first you will explore PHP as a product— its history, features, and
future.
In this hour, you will learn
What PHP is
About PHP's history
What improvements can be found in PHP4
Some options that add features to your PHP binary
Some reasons you should choose to work with PHP
What Is PHP?
PHP is a language that has outgrown its name. It was originally conceived as a setof macros to help coders maintain personal home pages, and its name grew from its
purpose. Since then, PHP's capabilities have been extended, taking it beyond a set
of utilities to a full-featured programming language, capable of managing huge
database-driven online environments.
As PHP's capabilities have grown, so too has its popularity. According to NetCraft
(http://www.netcraft.com), PHP was running on more than 1 million hosts in
November 1999. As of February 2000, that figure had already risen to 1.4 million
hosts. According to E-Soft, PHP is the most popular Apache module available,
beating even ModPerl.
PHP is now officially known as PHP: HyperText Preprocessor. It is a server-side
scripting language usually written in an HTML context. Unlike an ordinary HTML
page, a PHP script is not sent directly to a client by the server; instead, it is parsed
by the PHP binary or module. HTML elements in the script are left alone, but PHP
code is interpreted and executed. PHP code in a script can query databases, create
images, read and write files, talk to remote servers— the possibilities are endless.
The output from PHP code is combined with the HTML in the script and the result
sent to the user.
How Did PHP Evolve?
The first version of PHP was created by Rasmus Lerdorf in 1994 as a set of Webpublishing macros. These were released as the Personal Home Page Tools and later
rewritten and extended to include a package called the Form Interpreter (PHP/FI).
From a user's perspective, PHP/FI was already an attractive proposition, and its
popularity grew steadily. It also began to attract interest from the developer
community. By 1997, a team of programmers was working on the project.
The next release— PHP3— was born out of this collaborative effort. PHP3 was an
effective rewrite of PHP, with an entirely new parser created by Zeev Suraski and
Andi Gutmans, as well as differences in syntax and new features. This release
established PHP as one of the most exciting server scripting languages available,
and the growth in usage was enormous.
PHP's support for Apache and MySQL further secured its popularity. Apache is now
the most-used Web server in the world, and PHP3 can be compiled as an Apache
module. MySQL is a powerful free SQL database, and PHP provides a comprehensive
set of functions for working with it. The combination of Apache, MySQL, and PHP is
all but unbeatable.
That isn't to say that PHP is not designed to work in other environments and with
other tools. In fact, PHP supports a bewildering array of databases and servers.
The rise in popularity of PHP has coincided with a change of approach in Web
publishing. In the mid-1990s it was normal to build sites, even relatively large sites,
with hundreds of individual hard-coded HTML pages. Increasingly, though, site
publishers are harnessing the power of databases to manage their content more
effectively and to personalize their sites according to individual user preferences.
The use of databases to store content, and of a scripting language to retrieve this
data, will become further necessary as data is sent from a single source to multiple
environments, including mobile phones and PDAs, digital television, and broadband
Internet environments.
In this context, it is not surprising that a tool of PHP's sophistication and flexibility is
becoming so popular.
At the time of this writing, PHP4 is in its final beta stage and is due for release
shortly. By the time you read this book, PHP4 will be making waves!
What's New in PHP4
PHP4 introduces numerous new features that will make the programmer's life moreinteresting. Let's take a quick look at some of them.
A new foreach statement, similar to that found in Perl, makes it much easier to
loop through arrays. We will be using this for most of the array examples in this
book. Additionally, a raft of new array functions have been added, making arrays
easier to manipulate.
The language now includes the boolean data type.
A particularly useful feature of PHP3 was the capability to name form elements
as if they were elements in an array. The elements' names and values are then
made available to the code in array form. This feature has been extended to
support multidimensional arrays.
Support for object-oriented programming was somewhat rudimentary in PHP.
This is significantly extended in PHP4; for example, it is now possible to call an
overridden method from a child class.
PHP4 now provides native support for user sessions, using both cookies and the
query string. You can now "register" a variable with a session, and then access
the same variable name and value in subsequent user requests.
A new comparison operator (===) has been introduced that tests for
equivalence of type as well as equivalence of value.
New associative arrays containing server and environmental variables have
been made available, as well as a variable that holds information about uploaded
files.
PHP4 now provides built-in support for both Java and XML.
Although these and other features significantly improve the language, perhaps the
most significant change has taken place under the hood.
Teach Yourself PHP4
PCREs and Greediness 344
PCREs and Backslashed Characters 345
Finding Matches Globally with preg_match_all() 347
Using preg_replace() to Replace Patterns 350
Modifiers 351
Summary 354
Q&A 354
Workshop 355
Quiz 355
Activity 355
Hour 19: Saving State with Cookies and Query Strings 356
Overview 356
Cookies 356
The Anatomy of a Cookie 357
Setting a Cookie with PHP 358
Deleting a Cookie 360
Creating Session Cookies 360
An Example— Tracking Site Usage 361
Working with the Query String 369
Creating a Query String 370
Summary 372
Q&A 373
Workshop 373
Quiz 373
Activities 374
Hour 20: Saving State with Session Functions 375
Overview 375
What Are Session Functions? 375
Starting a Session with session_start() 376
Working with Session Variables 377
Destroying Sessions and Unsetting Variables 382
Passing Session IDs in the Query String 383
Encoding and Decoding Session Variables 384
Checking that a Session Variable Is Registered 385
Summary 385
Q&A 386
Workshop 386
Quiz 386
Activities 386
Hour 21: Working with the Server Environment 388
Overview 388
Opening Pipes to and from Processes with popen() 388
Running Commands with exec() 392
Running External Commands with system() or the Backtick
Operator 393
Plugging Security Holes with escapeshellcmd() 394
Running External Applications with passthru() 396
Calling an External CGI Script with the virtual() Function 397
Summary 398
Q&A 398
Workshop 399
Quiz 399
Activities 400
Hour 22: Debugging 401
Overview 401
Getting Information About PHP and Your Script 401
phpinfo() 401
Viewing Source with Syntax Coloring 405
PHP Error Messages 407
Writing Error Messages to a Log File 410
Getting the Error String 412
Manual Debugging 412
Common Errors 414
Summary 416
Q&A 417
Workshop 417
Quiz 417
Activity 417
Hour 23: An Example (Part 1) 418
Overview 418
The Brief 418
The Structure 418
Designing the Database 419
Design Choices 421
The Members Environment 421
join.php and dblib.inc 421
updateclub.php 429
membersmenu.php 437
login.php 438
updateevent.php 441
reviewevents.php 450
Summary 455
Q&A 455
Workshop 456
Quiz 456
Activity 456
Hour 24: An Example (Part 2) 457
Overview 457
The Events Diary Public Screens 457
viewevents.php 457
viewclubs.php 466
viewclub.php 470
viewevent.php 473
The Future 476
Summary 477
Q&A 477
Workshop 477
Quiz 477
Activities 478
PCREs and Backslashed Characters 345
Finding Matches Globally with preg_match_all() 347
Using preg_replace() to Replace Patterns 350
Modifiers 351
Summary 354
Q&A 354
Workshop 355
Quiz 355
Activity 355
Hour 19: Saving State with Cookies and Query Strings 356
Overview 356
Cookies 356
The Anatomy of a Cookie 357
Setting a Cookie with PHP 358
Deleting a Cookie 360
Creating Session Cookies 360
An Example— Tracking Site Usage 361
Working with the Query String 369
Creating a Query String 370
Summary 372
Q&A 373
Workshop 373
Quiz 373
Activities 374
Hour 20: Saving State with Session Functions 375
Overview 375
What Are Session Functions? 375
Starting a Session with session_start() 376
Working with Session Variables 377
Destroying Sessions and Unsetting Variables 382
Passing Session IDs in the Query String 383
Encoding and Decoding Session Variables 384
Checking that a Session Variable Is Registered 385
Summary 385
Q&A 386
Workshop 386
Quiz 386
Activities 386
Hour 21: Working with the Server Environment 388
Overview 388
Opening Pipes to and from Processes with popen() 388
Running Commands with exec() 392
Running External Commands with system() or the Backtick
Operator 393
Plugging Security Holes with escapeshellcmd() 394
Running External Applications with passthru() 396
Calling an External CGI Script with the virtual() Function 397
Summary 398
Q&A 398
Workshop 399
Quiz 399
Activities 400
Hour 22: Debugging 401
Overview 401
Getting Information About PHP and Your Script 401
phpinfo() 401
Viewing Source with Syntax Coloring 405
PHP Error Messages 407
Writing Error Messages to a Log File 410
Getting the Error String 412
Manual Debugging 412
Common Errors 414
Summary 416
Q&A 417
Workshop 417
Quiz 417
Activity 417
Hour 23: An Example (Part 1) 418
Overview 418
The Brief 418
The Structure 418
Designing the Database 419
Design Choices 421
The Members Environment 421
join.php and dblib.inc 421
updateclub.php 429
membersmenu.php 437
login.php 438
updateevent.php 441
reviewevents.php 450
Summary 455
Q&A 455
Workshop 456
Quiz 456
Activity 456
Hour 24: An Example (Part 2) 457
Overview 457
The Events Diary Public Screens 457
viewevents.php 457
viewclubs.php 466
viewclub.php 470
viewevent.php 473
The Future 476
Summary 477
Q&A 477
Workshop 477
Quiz 477
Activities 478
Teach Yourself PHP4
SAMS Teach Yourself PHP4 in 24 Hours 2
Acknowledgments 4
Tell Us What You Think! 4
Introduction 6
Who Should Read This Book? 6
How This Book Is Organized 6
Hour 1: PHP: From Home Page to Portal 22
Overview 22
What Is PHP? 22
How Did PHP Evolve? 23
What's New in PHP4 24
The Zend Engine 24
Why Choose PHP? 25
Speed of Development 25
PHP Is Open Source 26
Performance 26
Portability 26
Summary 27
Q&A 27
Workshop 27
Quiz 27
Activity 28
Hour 2: Installing PHP 29
Overview 29
Platforms, Servers, Databases, and PHP 29
Where to Find PHP and More 30
Installing PHP4 for Linux and Apache 30
Some configure Options 32
--enable-track-vars 32
--with-gd 32
--with-mysql 33
Configuring Apache 33
php.ini 34
short_open_tag 35
Error Reporting Directives 35
Variable Directives 36
Help! 36
Summary 38
Q&A 38
Workshop 38
Quiz 38
Activity 39
Hour 3: A First Script 40
Overview 40
Our First Script 40
Beginning and Ending a Block of PHP Statements 42
The print() Function 44
Combining HTML and PHP 44
Adding Comments to PHP Code 46
Summary 47
Q&A 47
Workshop 47
Quiz 48
Activity 48
Hour 4: The Building Blocks 49
Overview 49
Variables 49
Dynamic Variables 50
References to Variables 52
Data Types 53
Changing Type with settype() 55
Changing Type by Casting 57
Operators and Expressions 58
The Assignment Operator 59
Arithmetic Operators 59
The Concatenation Operator 60
More Assignment Operators 60
Comparison Operators 61
Creating More Complex Test Expressions with the Logical
Operators 62
Automatically Incrementing and Decrementing an Integer
Variable 63
Operator Precedence 65
Constants 66
Predefined Constants 67
Summary 67
Q&A 67
Workshop 68
Quiz 68
Activities 69
Hour 5: Going with the Flow 70
Overview 70
Switching Flow 70
The if Statement 70
Using the else Clause with the if Statement 72
Using the elseif Clause with the if Statement 73
The switch Statement 75
Using the ? Operator 77
Loops 78
The while Statement 78
The do..while Statement 79
The for Statement 80
Breaking Out of Loops with the break Statement 82
Skipping an Iteration with the continue Statement 84
Nesting Loops 85
Summary 86
Q&A 86
Hour 6: Functions 88
Overview 88
What Is a Function? 88
Calling Functions 88
Defining a Function 90
Returning Values from User-Defined Functions 92
Dynamic Function Calls 93
Variable Scope 94
Accessing Variables with the global Statement 95
Saving State Between Function Calls with the static Statement
98
More About Arguments 100
Setting Default Values for Arguments 100
Passing References to Variables to Functions 102
Summary 105
Q&A 105
Workshop 105
Quiz 106
Activity 107
Hour 7: Arrays 108
Overview 108
What Is an Array? 108
Creating Arrays 109
Defining Arrays with the array() Function 109
Defining or Adding to Arrays with the Array Identifier 110
Associative Arrays 110
Defining Associative Arrays with the array() Function 111
Directly Defining or Adding to an Associative Array 111
Multidimensional Arrays 112
Accessing Arrays 113
Getting the Size of an Array 113
Looping Through an Array 114
Looping Through an Associative Array 115
Outputting a Multidimensional Array 116
Manipulating Arrays 118
Joining Two Arrays with array_merge() 119
Adding Multiple Variables to an Array with array_push()
119
Removing the First Element of an Array with array_shift()
120
Slicing Arrays with array_slice() 121
Sorting Arrays 122
Sorting Numerically Indexed Arrays with sort() 122
Sorting an Associative Array by Value with asort() 123
Sorting an Associative Array by Key with ksort() 123
Summary 124
Q&A 124
Workshop 125
Quiz 125
Activities 125
Hour 8: Objects126
Overview 126
What Is an Object? 126
Creating an Object 127
Object Properties 128
Object Methods 129
An Example 132
Defining the Class's Properties 133
Creating a Constructor 133
The addRow() Method 134
The addRowAssocArray() Method 134
The output() Method 135
Bringing It All Together 136
What's Missing? 139
Why a Class? 139
Inheritance 140
Overriding the Method of a Parent Class 141
Calling an Overridden Method 143
Inheritance: An Example 144
Defining HTMLTable's Properties 144
Creating the Constructor 145
The setCellpadding() Method 146
The Output() Method 146
The Table and HTMLTable Classes in Their Entirety 147
Why Use Inheritance? 150
Summary 151
Q&A 152
Workshop 152
Quiz 152
Activities 153
Hour 9: Working with Forms 154
Overview 154
Global and Environment Variables 154
A Script to Acquire User Input 156
Accessing Input from Multiple SELECT Elements 157
Accessing All the Fields from a Form in an Associative Array
159
Distinguishing Between GET and POST Transactions 161
Combining HTML and PHP Code on a Single Page 162
Using Hidden Fields to Save State 165
Redirecting the User 167
File Upload Forms and Scripts 169
Summary 173
Q&A 173
Workshop 173
Quiz 174
Activities 174
Hour 10: Working with Files 175
Overview 175
Including Files with include() 175
Testing Files 178
Checking for Existence with file_exists() 179
A File or a Directory? 179
Checking the Status of a File 179
Determining File Size with filesize() 180
Getting Date Information About a File 180
Creating a Function That Performs Multiple File Tests 181
Creating and Deleting Files 183
Opening a File for Writing, Reading, or Appending 183
Reading from Files 184
Reading Lines from a File with fgets() and feof() 185
Reading Arbitrary Amounts of Data from a File with fread()
186
Reading Characters from a File with fgetc() 188
Writing or Appending to a File 189
Writing to a File with fwrite() or fputs() 189
Locking Files with flock() 190
Working with Directories 191
Creating Directories with mkdir() 191
Removing a Directory with rmdir() 192
Opening a Directory for Reading with opendir() 192
Reading the Contents of a Directory with readdir() 192
Summary 194
Q&A 194
Workshop 194
Quiz 194
Activities 195
Hour 11: Working with the DBM Functions 196
Overview 196
Opening a DBM Database 196
Adding Data to the Database 197
Amending Elements in a Database 198
Reading from a DBM Database 199
Determining Whether an Item Exists in a Database 201
Deleting an Item from a Database 201
Adding Complex Data Structures to a DBM Database 201
An Example 205
Summary 211
Q&A 211
Workshop 211
Quiz 211
Activities 212
Hour 12: Database Integration— MySQL 213
Overview 213
A (Very) Brief Introduction to SQL 213
Connecting to the Database Server 214
Selecting a Database 215
Finding Out About Errors 215
Adding Data to a Table 216
Acquiring the Value of an Automatically Incremented Field 220
Accessing Information 221
Finding the Number of Rows Found by a Query 221
Accessing a Resultset 222
Changing Data 225
Getting Information About Databases 227
Listing Databases 227
Listing the Tables Within a Database 229
Listing and Exploring Fields 229
Database Structure— Bringing It All Together 230
Summary 232
Q&A 233
Workshop 233
Quiz 234
Activities 234
Hour 13: Beyond the Box 235
Overview 235
Environmental Variables 235
A Brief Summary of an HTTP Client/Server Negotiation 238
The Request 238
The Response 241
Getting a Document from a Remote Address 243
Converting IP Addresses and Hostnames 244
Making a Network Connection 245
Making an NNTP Connection Using fsockopen() 249
Sending Mail with the mail() Function 252
Summary 253
Q&A 253
Workshop 254
Quiz 254
Activities 254
Hour 14: Working with Dynamic Images 256
Overview 256
Creating and Outputting Images 256
Acquiring Color 257
Drawing Lines 258
Applying Color Fills 259
Drawing an Arc 260
Drawing a Rectangle 261
Drawing a Polygon 262
Making a Color Transparent 263
Working with Text 264
Writing a String with imageTTFtext() 265
Testing Text Dimensions with imageTTFbox() 266
Bringing It Together 270
Summary 275
Q&A 275
Workshop 276
Quiz 276
Activities 276
Hour 15: Working with Dates 277
Overview 277
Getting the Date with time() 277
Converting a Time Stamp with getdate() 278
Converting a Time Stamp with date() 279
Creating Time Stamps with mktime() 282
Testing a Date with checkdate() 283
An Example 283
Checking User Input 284
Building the HTML Form 285
Creating the Calendar Table 287
Summary 292
Q&A 292
Workshop 292
Quiz 292
Activity 293
Hour 16: Working with Data 294
Overview 294
Data Types Revisited 294
A Recap 294
Converting Complex Types 295
Automatic Conversion of Data Types 297
Testing Data Types 298
More Ways of Changing Type 300
Why Are Data Types Important? 300
Testing for Absence and Emptiness 302
More About Arrays 303
An Alternative Approach to Traversing Arrays 304
Checking That a Value Exists in an Array 305
Removing an Element from an Array 306
Applying a Function to Every Element in an Array 306
Custom Sorting Arrays 307
Summary 311
Q&A 311
Workshop 311
Quiz 311
Activities 312
Hour 17: Working with Strings 313
Overview 313
Formatting Strings 313
Working with printf() 313
printf() and Type Specifiers 314
Padding Output with the Padding Specifier 317
Specifying a Field Width 318
Specifying Precision 319
Conversion Specifications: A Recap 320
Storing a Formatted String 322
Investigating Strings 323
A Note About Indexing Strings 323
Finding the Length of a String with strlen() 324
Finding a Substring Within a String with strstr() 324
Finding the Position of a Substring with strpos() 325
Extracting Part of a String with substr() 325
Tokenizing a String with strtok() 326
Manipulating Strings 328
Cleaning Up a String with trim() and ltrim() 328
Replacing a Portion of a String using substr_replace() 329
Replacing Substrings Using str_replace 329
Converting Case 329
Breaking Strings into Arrays with explode() 331
Summary 331
Q&A 332
Workshop 332
Quiz 332
Activities 333
Hour 18: Working with Regular Expressions 334
Overview 334
POSIX Regular Expression Functions 334
Using ereg() to Match Patterns in Strings 335
Using Quantifiers to Match a Character More Than Once
335
Matching Ranges of Characters with Character Classes 338
Working with Atoms 339
Branches 340
Anchoring a Regular Expression 340
The Membership Code Example Revisited 341
Using egrep_replace() to Replace Patterns in Strings 342
Using Back References with egrep_replace() 342
Using split() to Break Up Strings 343
Perl Compatible Regular Expressions (PCREs) 343
Matching Patterns with preg_match() 343
Acknowledgments 4
Tell Us What You Think! 4
Introduction 6
Who Should Read This Book? 6
How This Book Is Organized 6
Hour 1: PHP: From Home Page to Portal 22
Overview 22
What Is PHP? 22
How Did PHP Evolve? 23
What's New in PHP4 24
The Zend Engine 24
Why Choose PHP? 25
Speed of Development 25
PHP Is Open Source 26
Performance 26
Portability 26
Summary 27
Q&A 27
Workshop 27
Quiz 27
Activity 28
Hour 2: Installing PHP 29
Overview 29
Platforms, Servers, Databases, and PHP 29
Where to Find PHP and More 30
Installing PHP4 for Linux and Apache 30
Some configure Options 32
--enable-track-vars 32
--with-gd 32
--with-mysql 33
Configuring Apache 33
php.ini 34
short_open_tag 35
Error Reporting Directives 35
Variable Directives 36
Help! 36
Summary 38
Q&A 38
Workshop 38
Quiz 38
Activity 39
Hour 3: A First Script 40
Overview 40
Our First Script 40
Beginning and Ending a Block of PHP Statements 42
The print() Function 44
Combining HTML and PHP 44
Adding Comments to PHP Code 46
Summary 47
Q&A 47
Workshop 47
Quiz 48
Activity 48
Hour 4: The Building Blocks 49
Overview 49
Variables 49
Dynamic Variables 50
References to Variables 52
Data Types 53
Changing Type with settype() 55
Changing Type by Casting 57
Operators and Expressions 58
The Assignment Operator 59
Arithmetic Operators 59
The Concatenation Operator 60
More Assignment Operators 60
Comparison Operators 61
Creating More Complex Test Expressions with the Logical
Operators 62
Automatically Incrementing and Decrementing an Integer
Variable 63
Operator Precedence 65
Constants 66
Predefined Constants 67
Summary 67
Q&A 67
Workshop 68
Quiz 68
Activities 69
Hour 5: Going with the Flow 70
Overview 70
Switching Flow 70
The if Statement 70
Using the else Clause with the if Statement 72
Using the elseif Clause with the if Statement 73
The switch Statement 75
Using the ? Operator 77
Loops 78
The while Statement 78
The do..while Statement 79
The for Statement 80
Breaking Out of Loops with the break Statement 82
Skipping an Iteration with the continue Statement 84
Nesting Loops 85
Summary 86
Q&A 86
Hour 6: Functions 88
Overview 88
What Is a Function? 88
Calling Functions 88
Defining a Function 90
Returning Values from User-Defined Functions 92
Dynamic Function Calls 93
Variable Scope 94
Accessing Variables with the global Statement 95
Saving State Between Function Calls with the static Statement
98
More About Arguments 100
Setting Default Values for Arguments 100
Passing References to Variables to Functions 102
Summary 105
Q&A 105
Workshop 105
Quiz 106
Activity 107
Hour 7: Arrays 108
Overview 108
What Is an Array? 108
Creating Arrays 109
Defining Arrays with the array() Function 109
Defining or Adding to Arrays with the Array Identifier 110
Associative Arrays 110
Defining Associative Arrays with the array() Function 111
Directly Defining or Adding to an Associative Array 111
Multidimensional Arrays 112
Accessing Arrays 113
Getting the Size of an Array 113
Looping Through an Array 114
Looping Through an Associative Array 115
Outputting a Multidimensional Array 116
Manipulating Arrays 118
Joining Two Arrays with array_merge() 119
Adding Multiple Variables to an Array with array_push()
119
Removing the First Element of an Array with array_shift()
120
Slicing Arrays with array_slice() 121
Sorting Arrays 122
Sorting Numerically Indexed Arrays with sort() 122
Sorting an Associative Array by Value with asort() 123
Sorting an Associative Array by Key with ksort() 123
Summary 124
Q&A 124
Workshop 125
Quiz 125
Activities 125
Hour 8: Objects126
Overview 126
What Is an Object? 126
Creating an Object 127
Object Properties 128
Object Methods 129
An Example 132
Defining the Class's Properties 133
Creating a Constructor 133
The addRow() Method 134
The addRowAssocArray() Method 134
The output() Method 135
Bringing It All Together 136
What's Missing? 139
Why a Class? 139
Inheritance 140
Overriding the Method of a Parent Class 141
Calling an Overridden Method 143
Inheritance: An Example 144
Defining HTMLTable's Properties 144
Creating the Constructor 145
The setCellpadding() Method 146
The Output() Method 146
The Table and HTMLTable Classes in Their Entirety 147
Why Use Inheritance? 150
Summary 151
Q&A 152
Workshop 152
Quiz 152
Activities 153
Hour 9: Working with Forms 154
Overview 154
Global and Environment Variables 154
A Script to Acquire User Input 156
Accessing Input from Multiple SELECT Elements 157
Accessing All the Fields from a Form in an Associative Array
159
Distinguishing Between GET and POST Transactions 161
Combining HTML and PHP Code on a Single Page 162
Using Hidden Fields to Save State 165
Redirecting the User 167
File Upload Forms and Scripts 169
Summary 173
Q&A 173
Workshop 173
Quiz 174
Activities 174
Hour 10: Working with Files 175
Overview 175
Including Files with include() 175
Testing Files 178
Checking for Existence with file_exists() 179
A File or a Directory? 179
Checking the Status of a File 179
Determining File Size with filesize() 180
Getting Date Information About a File 180
Creating a Function That Performs Multiple File Tests 181
Creating and Deleting Files 183
Opening a File for Writing, Reading, or Appending 183
Reading from Files 184
Reading Lines from a File with fgets() and feof() 185
Reading Arbitrary Amounts of Data from a File with fread()
186
Reading Characters from a File with fgetc() 188
Writing or Appending to a File 189
Writing to a File with fwrite() or fputs() 189
Locking Files with flock() 190
Working with Directories 191
Creating Directories with mkdir() 191
Removing a Directory with rmdir() 192
Opening a Directory for Reading with opendir() 192
Reading the Contents of a Directory with readdir() 192
Summary 194
Q&A 194
Workshop 194
Quiz 194
Activities 195
Hour 11: Working with the DBM Functions 196
Overview 196
Opening a DBM Database 196
Adding Data to the Database 197
Amending Elements in a Database 198
Reading from a DBM Database 199
Determining Whether an Item Exists in a Database 201
Deleting an Item from a Database 201
Adding Complex Data Structures to a DBM Database 201
An Example 205
Summary 211
Q&A 211
Workshop 211
Quiz 211
Activities 212
Hour 12: Database Integration— MySQL 213
Overview 213
A (Very) Brief Introduction to SQL 213
Connecting to the Database Server 214
Selecting a Database 215
Finding Out About Errors 215
Adding Data to a Table 216
Acquiring the Value of an Automatically Incremented Field 220
Accessing Information 221
Finding the Number of Rows Found by a Query 221
Accessing a Resultset 222
Changing Data 225
Getting Information About Databases 227
Listing Databases 227
Listing the Tables Within a Database 229
Listing and Exploring Fields 229
Database Structure— Bringing It All Together 230
Summary 232
Q&A 233
Workshop 233
Quiz 234
Activities 234
Hour 13: Beyond the Box 235
Overview 235
Environmental Variables 235
A Brief Summary of an HTTP Client/Server Negotiation 238
The Request 238
The Response 241
Getting a Document from a Remote Address 243
Converting IP Addresses and Hostnames 244
Making a Network Connection 245
Making an NNTP Connection Using fsockopen() 249
Sending Mail with the mail() Function 252
Summary 253
Q&A 253
Workshop 254
Quiz 254
Activities 254
Hour 14: Working with Dynamic Images 256
Overview 256
Creating and Outputting Images 256
Acquiring Color 257
Drawing Lines 258
Applying Color Fills 259
Drawing an Arc 260
Drawing a Rectangle 261
Drawing a Polygon 262
Making a Color Transparent 263
Working with Text 264
Writing a String with imageTTFtext() 265
Testing Text Dimensions with imageTTFbox() 266
Bringing It Together 270
Summary 275
Q&A 275
Workshop 276
Quiz 276
Activities 276
Hour 15: Working with Dates 277
Overview 277
Getting the Date with time() 277
Converting a Time Stamp with getdate() 278
Converting a Time Stamp with date() 279
Creating Time Stamps with mktime() 282
Testing a Date with checkdate() 283
An Example 283
Checking User Input 284
Building the HTML Form 285
Creating the Calendar Table 287
Summary 292
Q&A 292
Workshop 292
Quiz 292
Activity 293
Hour 16: Working with Data 294
Overview 294
Data Types Revisited 294
A Recap 294
Converting Complex Types 295
Automatic Conversion of Data Types 297
Testing Data Types 298
More Ways of Changing Type 300
Why Are Data Types Important? 300
Testing for Absence and Emptiness 302
More About Arrays 303
An Alternative Approach to Traversing Arrays 304
Checking That a Value Exists in an Array 305
Removing an Element from an Array 306
Applying a Function to Every Element in an Array 306
Custom Sorting Arrays 307
Summary 311
Q&A 311
Workshop 311
Quiz 311
Activities 312
Hour 17: Working with Strings 313
Overview 313
Formatting Strings 313
Working with printf() 313
printf() and Type Specifiers 314
Padding Output with the Padding Specifier 317
Specifying a Field Width 318
Specifying Precision 319
Conversion Specifications: A Recap 320
Storing a Formatted String 322
Investigating Strings 323
A Note About Indexing Strings 323
Finding the Length of a String with strlen() 324
Finding a Substring Within a String with strstr() 324
Finding the Position of a Substring with strpos() 325
Extracting Part of a String with substr() 325
Tokenizing a String with strtok() 326
Manipulating Strings 328
Cleaning Up a String with trim() and ltrim() 328
Replacing a Portion of a String using substr_replace() 329
Replacing Substrings Using str_replace 329
Converting Case 329
Breaking Strings into Arrays with explode() 331
Summary 331
Q&A 332
Workshop 332
Quiz 332
Activities 333
Hour 18: Working with Regular Expressions 334
Overview 334
POSIX Regular Expression Functions 334
Using ereg() to Match Patterns in Strings 335
Using Quantifiers to Match a Character More Than Once
335
Matching Ranges of Characters with Character Classes 338
Working with Atoms 339
Branches 340
Anchoring a Regular Expression 340
The Membership Code Example Revisited 341
Using egrep_replace() to Replace Patterns in Strings 342
Using Back References with egrep_replace() 342
Using split() to Break Up Strings 343
Perl Compatible Regular Expressions (PCREs) 343
Matching Patterns with preg_match() 343
How This Book Is Organized
This book is divided into four parts:
Part 1 is an introduction to PHP4.
Part 2 covers the basic features of the language. Pay particular attention to this section if
you are new to programming.
Part 3 covers PHP4 in more detail, looking at the functions and techniques you will need to
become a proficient PHP programmer.
Part 4 illustrates a complete self-contained example.
Part 1 contains Hours 1 through 3 and handles the information you will need to get your first
script up and running:
Hour 1, "PHP: From Home Page to Portal," describes the history and capabilities of PHP
and looks at some of the compelling reasons for deciding to learn this scripting language.
Hour 2, "Installing PHP," explains how to install PHP on a UNIX system and discusses
some of the configuration options you might want to choose when compiling PHP. In this
hour, we also look at PHP configuration options.
Hour 3, "A First Script," looks at the different ways in which you can embed a PHP script in
a document and create a script that writes text to the user's browser.
Part 2 comprises Hours 4 through 8. In this part, you will learn the basic components of the
PHP language:
Hour 4, "The Building Blocks," covers the basics of PHP. You will learn about variables,
data types, operators, and expressions.
Hour 5, "Going with the Flow," covers the syntax for controlling program flow in your scripts.
In addition to if and switch constructs, you will learn about loops using for and while
statements.
Hour 6, "Functions," explores the use of functions to organize your code.
Hour 7, "Arrays," discusses the array data type that can be used to hold list information.
We will also look at some of the functions that PHP4 provides to manipulate arrays.
Hour 8, "Objects," introduces PHP4's support for classes and objects. Throughout the
course of the hour, we will develop a working example.
Part 3 consists of Hours 9 through 22. In this part, you will come to grips with the features and
techniques of the language:
Hour 9, "Working with Forms," introduces the dimension of user input through the
mechanism of the HTML form. You will learn how to gather data submitted via a form.
Hour 10, "Working with Files," shows you how to work with files and directories on the local
machine.
Hour 11, "Working with the DBM Functions," demonstrates PHP4's support for DBM
database systems, versions of which are available on most systems.
Hour 12, "Database Integration— MySQL," provides a brief introduction to SQL syntax and
introduces the PHP4 functions that can be used to work with the MySQL database.
Hour 13, "Beyond the Box," covers some of the details of HTTP requests and looks at PHP
network functions.
Hour 14, "Working with Dynamic Images" explores PHP's image functions. With these, you
can create GIF or PNG files dynamically.
Hour 15, "Working with Dates," covers the functions and techniques you can use for date
arithmetic. We create a calendar example.
Hour 16, "Working with Data," revisits data types and explores some more of the functions
you can use to work with data in your scripts. More array functions are also covered.
Hour 17, "Working with Strings," covers the functions that you can use to manipulate
strings.
Hour 18, "Working with Regular Expressions," introduces regular expression functions.
You can use these to find and replace complex patterns in strings.
Hour 19, "Saving State with Cookies and Query Strings," shows you some techniques for
passing information across scripts and requests.
Hour 20, "Saving State with Session Functions," extends the techniques explored in Hour
19, using PHP4's built-in session functions.
Hour 21, "Working with the Server Environment," shows you how to call external programs
from your scripts and incorporate their output into your own.
Hour 22, "Debugging," shows you some techniques that you can use to track down
problems in your code. We also examine some common errors.
Part 4 consists of Hours 23 and 24. In these, we build a working example that incorporates
some of the techniques that were introduced earlier in the book.
Hour 23, "An Example (Part 1)," creates a brief for a club listings script. We build the code
that will allow users to create accounts and enter listings.
Hour 24, "An Example (Part 2)," concludes the project, building the code for nonmembers
to browse the listings and look at club profiles.
Part 1 is an introduction to PHP4.
Part 2 covers the basic features of the language. Pay particular attention to this section if
you are new to programming.
Part 3 covers PHP4 in more detail, looking at the functions and techniques you will need to
become a proficient PHP programmer.
Part 4 illustrates a complete self-contained example.
Part 1 contains Hours 1 through 3 and handles the information you will need to get your first
script up and running:
Hour 1, "PHP: From Home Page to Portal," describes the history and capabilities of PHP
and looks at some of the compelling reasons for deciding to learn this scripting language.
Hour 2, "Installing PHP," explains how to install PHP on a UNIX system and discusses
some of the configuration options you might want to choose when compiling PHP. In this
hour, we also look at PHP configuration options.
Hour 3, "A First Script," looks at the different ways in which you can embed a PHP script in
a document and create a script that writes text to the user's browser.
Part 2 comprises Hours 4 through 8. In this part, you will learn the basic components of the
PHP language:
Hour 4, "The Building Blocks," covers the basics of PHP. You will learn about variables,
data types, operators, and expressions.
Hour 5, "Going with the Flow," covers the syntax for controlling program flow in your scripts.
In addition to if and switch constructs, you will learn about loops using for and while
statements.
Hour 6, "Functions," explores the use of functions to organize your code.
Hour 7, "Arrays," discusses the array data type that can be used to hold list information.
We will also look at some of the functions that PHP4 provides to manipulate arrays.
Hour 8, "Objects," introduces PHP4's support for classes and objects. Throughout the
course of the hour, we will develop a working example.
Part 3 consists of Hours 9 through 22. In this part, you will come to grips with the features and
techniques of the language:
Hour 9, "Working with Forms," introduces the dimension of user input through the
mechanism of the HTML form. You will learn how to gather data submitted via a form.
Hour 10, "Working with Files," shows you how to work with files and directories on the local
machine.
Hour 11, "Working with the DBM Functions," demonstrates PHP4's support for DBM
database systems, versions of which are available on most systems.
Hour 12, "Database Integration— MySQL," provides a brief introduction to SQL syntax and
introduces the PHP4 functions that can be used to work with the MySQL database.
Hour 13, "Beyond the Box," covers some of the details of HTTP requests and looks at PHP
network functions.
Hour 14, "Working with Dynamic Images" explores PHP's image functions. With these, you
can create GIF or PNG files dynamically.
Hour 15, "Working with Dates," covers the functions and techniques you can use for date
arithmetic. We create a calendar example.
Hour 16, "Working with Data," revisits data types and explores some more of the functions
you can use to work with data in your scripts. More array functions are also covered.
Hour 17, "Working with Strings," covers the functions that you can use to manipulate
strings.
Hour 18, "Working with Regular Expressions," introduces regular expression functions.
You can use these to find and replace complex patterns in strings.
Hour 19, "Saving State with Cookies and Query Strings," shows you some techniques for
passing information across scripts and requests.
Hour 20, "Saving State with Session Functions," extends the techniques explored in Hour
19, using PHP4's built-in session functions.
Hour 21, "Working with the Server Environment," shows you how to call external programs
from your scripts and incorporate their output into your own.
Hour 22, "Debugging," shows you some techniques that you can use to track down
problems in your code. We also examine some common errors.
Part 4 consists of Hours 23 and 24. In these, we build a working example that incorporates
some of the techniques that were introduced earlier in the book.
Hour 23, "An Example (Part 1)," creates a brief for a club listings script. We build the code
that will allow users to create accounts and enter listings.
Hour 24, "An Example (Part 2)," concludes the project, building the code for nonmembers
to browse the listings and look at club profiles.
Subscribe to:
Posts (Atom)