O'reilly - An Introduction To Php

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View O'reilly - An Introduction To Php as PDF for free.

More details

  • Words: 24,504
  • Pages: 85
O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/02/22/php_foundations.html See this if you're having trouble printing code examples

An Introduction to PHP 02/22/2001

What exactly is PHP anyway? PHP is short for what is officially called "PHP: Hypertext Preprocessor." PHP was created by Rasmus Lerdorf, a developer who needed a tool to keep track of who was looking at his resume. The first version of Lerdorf's preprocessor (known then as PHP/FI) was released in 1994. Since then, PHP has become popular in the open−source community and was renamed PHP with the release of version 3.0. PHP is now at version 4.0 and is used by over 3 million web sites on the Internet. PHP represents a robust open−source development language that provides the tools and flexibility to accomplish virtually any task. PHP is an embedded language which means developers can jump between raw HTML code and PHP without sacrificing readability. Beyond its basic syntax, PHP also boasts a wide range of interfaces allowing it to communicate with everything from other web pages, to databases including ODBC, and other programming languages such as Java or COM.

So what can it do? At a fundamental level, PHP has all of the features of a complete programming language (control structures, repetitive tasks, and variables) but perhaps one of its most powerful features is database access. With PHP it is possible to access over 19 different types of databases and manipulate data within those databases based on input from the user via a web page. You can also send e−mail, work with newsgroups, and actually open a connection to another web site −− and get or send data with it. If you are already familiar with ASP development, PHP can also communicate with other server−side languages such as Java and use COM interfaces. Do you have a guestbook on your web site? Do you subscribe to a third−party service that provides statistics on site visitors? Would you like to know how a user got into your web page (the specific page), where they visited on your web site, and what page they left from? With PHP, such tasks are almost trivial. PHP provides the means to do everything from processing data to generating graphics on the fly.

An Introduction to PHP

1

O'Reilly Network: An Introduction to PHP

How does it work? For those of you who are familiar with web development, the term CGI (Common Gateway Interface) may be familiar to you. CGI provides a way for developers to write computer programs that can construct HTML and process data from web pages dynamically. Before CGI, web developers were forced to write static HTML pages that required tedious manual updates. PHP is a customized, embedded CGI language. Because PHP is server−side technology, the person viewing the web page needs no special programs or browser plug−ins for PHP to work. PHP is compatible with all major web browsers, and although it is classified as a CGI, PHP is a tool that provides much more power. It allows a web developer to dynamically construct a web page based on data gathered from a third source (a database or otherwise) and then communicate that data through almost any means provided by the Internet. The real benefit of this is the developer can do these things with little or no knowledge of the inner workings between the CGI and the database they are communicating with. As mentioned before PHP is a hypertext preprocessor. In a less technical sense, this means that when a user points a browser at your web site, PHP gets a chance to make "last−minute" changes to the page before the user sees it (See Figure 1).

How does it work?

2

O'Reilly Network: An Introduction to PHP

Figure 1. Web request processing with and without PHP. A web server with PHP installed takes the extra step of allowing PHP to process the requested document before displaying it to the user. From this extra step PHP can then perform any operation including access the database, send e−mail messages, or open a connection to another Internet service (such as another web server). All professional web sites including search engines and web−based e−mail services use this technology model where the server has an intermediate−processing step between the actual document and the user −− without this model those sites could not exist.

How do I begin using PHP? To use PHP (or any other server−side web scripting language), it must be installed on your web server. PHP's parser comes in two flavors −− a CGI executable and a module for the Apache web server. If you do not own your own web server, a list of PHP−enabled web hosts is available from php.net. If you are a web−hosting provider, or have access to your own web server, download PHP from the official PHP site along with complete installation documentation. Note: To take full advantage of all of PHP's functionality, other freeware third−party How do I begin using PHP?

3

O'Reilly Network: An Introduction to PHP software may also need to be installed. Consult the PHP documentation for more information on PHP functions and where to find the appropriate third−party software. I have PHP installed, how do I use it? If you already have PHP installed but want to know how to program in PHP there are many tutorials available. The best place to start learning PHP is from this web site or the PHP homepage. John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Discuss this article in the O'Reilly Network PHP Forum. Return to the PHP DevCenter.

oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

How do I begin using PHP?

4

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/03/08/php_foundations.html See this if you're having trouble printing code examples

Basic PHP Syntax

by John Coggeshall 03/08/2001 This article covers basic PHP syntax, including variable usage, variable types, and several ways of printing variables to the web browser.

Embedded code blocks PHP is an embedded web development language with many similarities to commercial packages such as Microsoft's Active Server Pages (ASP) or Cold Fusion. One of the similarities between PHP and these packages (especially ASP) is the ability to jump between PHP and HTML code quickly and easily. The basic syntax to jump in and out of PHP follows: My first PHP page This is normal HTML code Back into normal HTML

In this example, we see that PHP code is signified by the use of the to signify the end of the code block. Although this a completely acceptable method of encapsulating your PHP code there are many other ways that are all, as far as syntax is concerned, correct. Here are some other ways to mark PHP code blocks.

Basic PHP Syntax

5

O'Reilly Network: An Introduction to PHP Valid syntax to indicate a PHP code block

Standard PHP syntax



Shorthand version

<% ... %>

ASP−style PHP syntax

<SCRIPT LANGUAGE="PHP"> Standard script syntax So, for example, let's say that you are a web developer who uses a third−party software package to do the actual layout of your web pages. Under normal conditions, PHP's standard syntax would cause unpredictable results in your layout software. So, to remedy this you could use the HTML script standard syntax instead of the PHP standard: Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Introduction to PHP Objects, Part 1 My first PHP page This is normal HTML code <script language="PHP"> // PHP code goes here // This code block syntax won't break // graphical web layout software Back into normal HTML

Basic PHP Syntax

6

O'Reilly Network: An Introduction to PHP

General syntax Before we discuss variables, we should begin with some general PHP syntax rules. First, all single−line statements must conclude with a semicolon. In addition, statements that exceed a single line (such as most conditionals) must be surrounded by { and } characters. Finally, the double forward slash (//) represents a comment and everything past those characters until the end of the line will be ignored by PHP. Now, on to the variables in PHP!

Variables in PHP PHP denotes all of its variables by using the $ operator followed by any combination of characters as long as these rules are followed: • The variable name starts with a letter or an underscore (_) • It is followed by any combination of letters, numbers, and underscores Note: A letter is defined as the lowercase and uppercase characters "a" through "z" as well as any character with an ASCII value between 127 and 255 To define a variable, you can either define it with a value or by using the var operator. Example:

In this example, the variable $myvar is assigned the string value "foo" while the second variable we defined $my_second_var is empty and contains nothing. For a comparison, we will now give you some examples of invalid PHP variables:

Now that we have learned proper syntax for our variables, we can move on the variable types and functions.

Types of variables PHP is what is known as a "loosely typed" language. What that means is any given variable can be an integer, floating−point number, string, object, or an array. In this article, we will only be discussing the first three types. General syntax

7

O'Reilly Network: An Introduction to PHP Type 1: The integer An integer is the basic mathematical datatype and represents any whole number and usually can be any value from minus 2 billion to 2 billion. When assigning an integer value, three different types of notation can be used: decimal (regular base 10), hexadecimal (base 16), or octal (base 8). Usually, only the normal decimal notation is used but there are special cases when a hexadecimal or octal notation makes life easier for the developer.

Type 2: The floating−point number Floating−point numbers are the second mathematical datatype PHP provides. A floating−point number represents any value that contains a decimal point. Floating−point numbers are somewhat unreliable in the sense that the value stored in them is not always the exact value the developer expects, but for now we will ignore that. Instead, we will focus on the notation used to assign a variable a floating−point value. Floating−point numbers can be expressed in two different types of notation: decimal and scientific.
// Standard decimal notation // Scientific notation

?>

Type 3: The string A string is a datatype we first used in our original examples to assign values to variables. A string can be any combination of letters, numbers, or special symbols as long as consideration is given to characters that have functions in PHP. Before we consider special cases, let's first discuss the difference between the two string notations: the single and double quote. In every case where you may want to assign a string value to a variable, the value itself must begin and end with a pair of either single (' ') or double (" ") quotes.

In this example, both variables would simply be assigned a value within the single or double quotes. However, when double quotes are used, PHP will first look inside the string for any references to variables that may exist. If any references are found, they are replaced with values before being assigned to the designated variable. Conversely, when dealing with single−quoted strings, PHP simply takes the string as−is and assigns it to the designated variable. Types of variables

8

O'Reilly Network: An Introduction to PHP
// Assign the variable myint to 10

$string_one = 'The value of myint is $myint'; $string_two = "The value of myint is $myint"; ?>

Consider the above example. In the first line, we simply assign the integer value "10" to the variable $myint. Then, we assign two more variables $string_one and $string_two. These are identical except $string_one is stored using single quotes and $string_two is stored using double quotes. In this example, the values within the two strings are as follows: • $string_one = The value of myint is $myint • $string_two = The value of myint is 10 Notice that, when the value of $string_two is displayed, the variable $myint was replaced with the value "10". In the single−quoted string, however, the actual string $myint was stored.

Special characters Next, we will discuss "special" characters. Here's a common scenario: You are developing a web site and find yourself needing to store the double−quote character itself (") as a string within another variable. You can't simply place the double quote within a set of double quotes because it will cause an error in PHP. To overcome this dilemma, a method called an "escape" is used to allow developers to store this special character along with others in strings. To escape a character, the character is simply prefixed by the backslash character (\). So, to store the double−quote character in a string, we would instead tell PHP to store the string \" instead. Here is an example:

The first attempt is incorrect due to the use of "un−escaped" double quotes within the string itself. The proper syntax for storing this string is illustrated in the second example where the quotes surrounding the word "escape" are properly coded. Below is a table of other special characters that require a backslash. Note: Although attempting to store a un−escaped double−quote within a string will cause an error, storing a single−quote within a double−quoted string will not throw an error and is completely acceptable. Valid back−slashed characters \n

linefeed (LF or 0x0A in ASCII)

\r

carriage return (CR or 0x0D in ASCII)

\t

horizontal tab (HT or 0x09 in ASCII)

\\

backslash

Special characters

9

O'Reilly Network: An Introduction to PHP \$

dollar sign

\"

double−quote

\[0−7]{1,3}

the sequence of characters matching the regular expression is a character in octal notation

\x[0−9A−Fa−f]{1,2}

the sequence of characters matching the regular expression is a character in hexadecimal notation

John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Discuss this article in the O'Reilly Network PHP Forum. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

Special characters

10

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/03/22/php_foundations.html See this if you're having trouble printing code examples

Variable Manipulation and Output 03/22/2001 Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Introduction to PHP Objects, Part 1 This article will conclude our discussion of variables in PHP by presenting the numerous ways that atomic PHP variables can be manipulated and accessed within PHP scripts. We'll also look at the echo command and use it to create our first PHP script that truly outputs dynamic content to the user.

Basic manipulations Now that we have a better idea of the types of variables in PHP and are familiar with how to use them, we will begin discussing how these variables can interact and be manipulated. As with our introduction to the types of variables in PHP, we will begin with the mathematical operators. Basic mathematics in PHP To begin our introduction into variable manipulation, we will start with the basic mathematical abilities of PHP using standard integer variables. For the most part, the syntax and logic in this section is straightforward and will only be covered briefly to clarify any confusion that may exist. Consider the following:
Variable Manipulation and Output

11

O'Reilly Network: An Introduction to PHP $number = 10; $foo = 2; $answer = $number + $foo; ?>

This is an example of a basic mathematical operation between two integers in PHP. As expected, the variable $number is added to the variable $foo with the sum of these two numbers (10 + 2 = 12) being stored in the variable $answer. Now, what if we wanted to subtract $answer by another number such as 5 (assume $answer is 12)?
// Assume $answer exists and is equal to // $number + $foo (10 + 2 = 12) $answer = $answer − 5;

?>

In this example, we are taking our previous value $answer, and subtracting it by the constant value 5 and then storing the resulting number back into the variable $answer. For those who have no programming experience, this example can be quite confusing! How can you take a variable, subtract it by another number and store the answer to that variable into the same variable you just used in your subtraction? The answer is that PHP will always evaluate a statement before any assignments are made −− that is, PHP will use the old value of $answer to do the mathematics before replacing it with the new value. Therefore, the value of answer should be 12 − 5 = 7, and it is! Simplified syntax The situation presented above −− where a variable is used in a mathematical statement and the result of the statement is stored back into the variable used originally −− is very common. Usually, the mathematical tasks performed in an application are very simple and, to make such tasks easier, the following statements are all allowed in PHP:

PHP also allows the use of parentheses within mathematical statements. An example:
((4 + 2) * 5)/2 = 30 30/2 = 15

Variable Manipulation and Output

12

O'Reilly Network: An Introduction to PHP ?>

Floating−point variables As mentioned in my previous article, floating−point numbers may not always store and return the values as expected. For example, a floating−point statement that evaluates to the value 7.99999999 may be perceived as the value 7 on some systems when converted to an integer rather than the expected value of 8. For more information regarding the particulars of this on your specific system consult the PHP manual. Beyond the special consideration that must be taken when dealing with floating−point numbers, they conform to all of the same mathematical syntax as their integer counterparts.

String manipulation When dealing with strings, it is often necessary to manipulate them in a number of ways. PHP provides a small army of string manipulation functions that provide tools for nearly every circumstance. (A list of these functions can be found online at the PHP web site.) Although the majority of string manipulation is done through function calls, there is a syntax that is worth discussion. When dealing with strings, it is sometimes useful if not necessary to take two strings and combine them head−to−tail into a single string. To do this, we use the period operator (".") to combine strings just as we used a math operator (such as addition). Example:

Also note that the period operator can be used in a syntax similar to the one illustrated in the integer examples:
to $bar my "; name "; is "; John ";

?>

As expected, the resulting value of $bar will be "Hello, my name is John".

Outputting to the browser One of the most fundamental aspects of web development in PHP is outputting to the browser. Although in a technical sense you are outputting to the browser simply by sending them the content of a web page, when we String manipulation

13

O'Reilly Network: An Introduction to PHP discuss output we will focus on sending variables that we construct and manipulate in PHP to the browser dynamically. Basic output with echo The first function we will discuss, echo, is the most basic output function available to PHP. With echo, you can send any data to the web browser (variable or constant). Its syntax follows: echo ;

In example: My first PHP page "; $my_var = "Hello, PHP!

"; $msg = $my_msg.$my_var; echo $msg; $my_var = "Goodbye, PHP!"; echo $my_var; ?>

This example pulls together a number of the concepts that we have been talking about in the past articles. Above, we have a PHP script embedded in a HTML document. In this PHP script, we are taking two variables ($my_msg and $my_var) and assigning them values. These two variables are then combined into a single variable and stored into $msg which is then output to the browser using the echo function. Then the value of $my_var is changed and a second output is made to the browser showing its new value. The PHP script then terminates, returning the server to outputting straight HTML. The resulting output is equivalent to the following static HTML page: My first PHP page This is my first PHP output!
Hello, PHP!

Goodbye, PHP!

Which of course outputs to the browser as: This is my first PHP output!

String manipulation

14

O'Reilly Network: An Introduction to PHP Hello, PHP! Goodbye, PHP!

Notice that in our PHP code to output the text we included the HTML tag
where we wanted a line break within the PHP variable. Without such HTML tags within our variables, the output would have looked something like this: This is my first PHP output!Hello, PHP!Goodbye, PHP!

Simplified variable output Although the echo function is the most basic function used to output to the browser, there is an easier way to output single variables in PHP. The best way to illustrate this is by rewriting our original example: My first PHP page "; $my_var = "Hello, PHP!

"; ?>




Although the above example looks more complicated than the original, it illustrates an important element of PHP syntax −− the method of output. This example may be different in syntax, but the output to the browser is identical. Using this method is no more efficient or effective than using echo, but exists to save keystrokes for the developer needing to perform the very common task of outputting a variable. John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

Simplified variable output

15

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/04/05/php_foundations.html See this if you're having trouble printing code examples

Basic Control Structures 04/05/2001 This article covers the basics of program control structures, including conditional statements and looping using the if and while statements in PHP. It also contains a brief note regarding embedding code blocks within other code blocks.

Conditional blocks One of the most fundamental tools of any true programming language is the ability to control what code gets executed and under what conditions by using a conditional block. A conditional block can be thought of in English language terms as "if this, then that; otherwise something else". For instance: "If Billy has 5 dollars in his hand, then buy a candy bar; otherwise, cry." Today, we will discuss the basic structure and use of conditional blocks in our programs and introduce the ways we can use conditional blocks to compare one variable to another. For this article, we'll be taking a look at the following PHP code: "; } else { echo "Billy could not afford any candy.
"; echo "Billy is crying.
"; } echo "Billy went home."; if($have_candy) { echo "Billy ate his candy bar at home";

Basic Control Structures

16

O'Reilly Network: An Introduction to PHP } ?>

The above is our first example of a conditional block and is the PHP version of our example mentioned in the introduction. When this code is executed, what will happen? Before we can properly answer this question, we first must learn some new syntax.

The if statement The if statement is the most fundamental control structure available. Its function is to execute a "block" of code if and only if the statement provided to it is a "true" statement. In order to determine if a statement is indeed true, some comparison operators and their meaning must be introduced. Before that is covered, let's take a look at the if statement in general form: If(conditions) { // Code if condition is true } [ else ] { // Code if condition is false }

Note: The presence of the brackets [ ] around the else portion of this general form indicates that it is not necessary to be a valid conditional. Another, incomplete general form of the if statement would be: If(conditions) { // Code if condition is true }

Now that we have a better understanding of the general form of an if statement, we can go back and examine our example. The parentheses of the first if statement contain $dollars == 5. Although it appears as if we are attempting (incorrectly) to assign the value 5 to the variable $dollars, in reality we are providing an execution condition for the code contained with the if statement. This condition (which can be read as $dollars must equal the value 5) will determine what code within that if statement is executed. There are many different comparison operators that are the foundation for building our conditionals, and they are listed below: Comparison operators in PHP $a == $b $a is equal to $b $a != $b $a is not equal to $b $a < $b

$a is less than $b

$a > $b

$a is greater than $b

$a <= $b $a is less than or equal to $b $a >= $b $a is greater than or equal to $b Looking back at our earlier example, we are now able to determine how our PHP code will behave. First, we initialized the variable $dollars with a value of 4 and the variable $have_candy with a Boolean value of false. Then, we compared the value of $dollars to see if it was equal to the constant value of 5. Since the value of dollars (4) was not equal to 5, $have_candy remained false and the output to the web browser The if statement

17

O'Reilly Network: An Introduction to PHP was: Billy could not afford any candy. Billy is crying. Billy went home. What if we changed our conditions for the if statement? For instance, if we changed our conditional from equal (==) to less than or equal (<=), $have_candy would then be set to true and our output would be: Billy has a candy bar Billy went home. Billy ate his candy bar at home. Notice the behavior of the second if statement, which outputs "Billy ate his candy bar at home." In the first example, the variable $have_candy was false and, since there was no else statement for the second conditional block, it was simply skipped altogether. Another interesting behavior of the second if statement is the lack of any indication of what the variable $have_candy is being compared to. In cases such as this, where a variable is provided as the only condition to an if statement, the value of the variable is used to determine the behavior of the conditional. Therefore, since $have_candy had a value of true (referring to the second example), the conditional is considered to be true and, as expected, in the second example the code was executed.

Basic looping If the ability to control what code in a script is run and under what conditions is the first fundamental part of any true programming language, then the ability to execute the same code multiple times is a very, very close second. Let's say you would like to write a script that outputs the numbers 1 through 5 on the web browser. How would you do this? One example would be:
"1

/>"; />"; />"; />"; />";

?>

Although that doesn't seem too overly complicated, consider outputting the numbers 1 through 100, or 1000, or even 1,000,000? Obviously, writing a script that contains a million echo statements is, at best, impractical. Beyond that, there are many more complex examples where the same piece of code is executed numerous times that would be impossible to duplicate in such an inefficient fashion as above. It is with this in mind that we introduce the while statement.

The while statement The while statement is the most fundamental looping mechanism available to a PHP programmer. Although fundamentally different, it holds many similarities in syntax to an if statement, with the only real difference being that a segment of code within a while block will be executed as long as the condition in the while block is met (see figure 1). The syntax for a while loop is as follows: Basic looping

18

O'Reilly Network: An Introduction to PHP While(conditions) { // This code will execute until the conditions // provided no longer evaluates to true }

Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Introduction to PHP Objects, Part 1

Figure 1. Processing of a while loop. Looking at our earlier counting example, a much easier and more effective way to produce the same results using a while loop would be: "; $count++; } ?>

Basic looping

19

O'Reilly Network: An Introduction to PHP As expected, the output for both examples is identical. Notice that by simply changing a few small aspects of this example, you can change the behavior of the while loop completely. (For example, instead of $count++ you could use $count += 2 and display only odd numbers.)

Infinite loops What would have happened if we had forgotten to include the increment of $count in the body of our while loop? The variable $count would have never been incremented and therefore would have never reached the value of 5. Because of this, the conditional $count <= 5 would always evaluate to true and the program would never leave the while loop. This situation, called an infinite loop, is a common mistake by many programmers. Be careful when using while loops (or any type of loop discussed) to ensure that the program will eventually terminate. Note: PHP will not allow a program to run longer than a specific period of time (determined by the system administrator) without special settings. Usually the default settings give any reasonable script enough time to complete without premature termination. However, there are times when a processor−intensive script's running time exceeds the default maximum time. In these cases, please consult the PHP documentation for instructions on how to extend the run time from within your PHP scripts. In my next article I will discuss with you a more specialized version of a while loop called a for loop, as well as the methods behind multi−condition if statements.

Notes on embedding code blocks When writing programs, it is often common to embed conditions, or even other loops, within other loops or conditionals. For example, the following will count from 1 to 5 but display the string "Magic Number!" before it displays the number 3: "; } echo $count."
"; $count++; } ?>

This feature is an important part of the language and is used quite frequently; it can be used in any syntax where a code block (distinguished by the { and } symbols) exists. John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Infinite loops

20

O'Reilly Network: An Introduction to PHP Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

Infinite loops

21

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/04/19/php_foundations.html See this if you're having trouble printing code examples

Advanced Control Structures 04/19/2001 Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Introduction to PHP Objects, Part 1 This article will cover advanced control structures and techniques, including multi−conditional if statements and an introduction to the for statement.

The 'for' loop In our previous articles, we discussed using a while loop as a means to repeat a block of code until the condition it provided is determined to be false. Although useful, while loops are used primarily when you don’t initially know how many times you want to execute the code block. The for statement is another repetition statement designed to be used when executing a code block a specific number of times. The syntax for a for loop is: For(initialization; condition; increment) { // Code to loop }

Unlike the while loop, a for loop contains three parts separated by semicolons. When a for statement Advanced Control Structures

22

O'Reilly Network: An Introduction to PHP executes, the initialization statement is automatically executed. Then, once the initialization statement has finished, the condition provided is evaluated. If this condition is true, the code block enclosed within the for statement is then executed. After the code within the loop has been executed, the increment statement is evaluated and the condition is then re−evaluated. Note that in a for loop, the initialization statement is only evaluated once −− before any code within the loop is evaluated −− but the increment portion is evaluated after each iteration of the loop. This looping process (evaluate condition, evaluate block, evaluate increment statement) is continued until the conditions provided are false and the loop ends (See Figure 1).

Figure 1. Processing of a "for" loop. Now that we have an idea of how a for statement works, let's see it in action by looking at the earlier example we used to demonstrate the workings of a while loop where we wanted to display a count of all the numbers between 1 and 5: "; } ?>

As expected, the output is identical to the while loop and displays the numbers 1 through 5. Again note that the increment statement ($L++) could be any valid math statement. For example, we could count backwards from 5 to 1 by using the following: = 1; $L−−) { echo $L."
"; }

Advanced Control Structures

23

O'Reilly Network: An Introduction to PHP ?>

Multi−conditional 'if' statements In programming, it is often necessary to execute a piece of code based on more than one condition. To accomplish this, PHP provides a few ways to evaluate a code block based on multiple conditions. Although the desired result can be achieved by simply embedding if statements within other if statements, this is often an excessive and confusing way to accomplish the desired effect. To help remedy this problem, special conditional operators "and" (&&) and "or" (||) are provided. These operators separate multiple conditions within an if statement and determine the final outcome of an evaluation. For example, consider the following statement: If Billy has $5, and his mom says it’s okay, he can have a candy bar. We already learned how to code this conditional statement by embedding two if statements as shown below: If($dollars >= 5) { If($mom_okay) { // Code when both conditions are true } }

We see that in order for Billy to have a candy bar, two conditions must be met: He must have money ($5 minimum) and his mother must agree. In PHP, such a statement could also be written as follows: If( ($dollars >= 5) && ($mom_okay) ) { // Code if both conditions are true }

As you can see, we have used the "and" operator to combine the original two separate conditional statements into a single conditional statement. Note: The use of parentheses in the above example is to ensure that each separate conditional statement is evaluated properly before the results of those conditions are evaluated through the "and" operator. If all conditions that are combined using the "and" operator must evaluate to "true" for the statement to be true, then when using the "or" operator only a single condition of the combined conditions must evaluate to "true" in order for the statement to be true. For example, if we modified our example to read: If Billy has $5 or if his mom agrees, he can have a candy bar. Using basic if statements, our code would resemble the following: If($dollars >= 5) { // Code if condition is true } If($mom_okay) { // Identical to code in the first conditional }

In this example, the complexity and inefficiency of our code increases because we have to duplicate code Multi−conditional 'if' statements

24

O'Reilly Network: An Introduction to PHP twice. To make this code more efficient, we can combine these two conditional statements using our new conditional operators. The same statement using these operators would look something like this: If( ($dollars >= 5) || ($mom_okay) ) { // Code if either condition is true }

This multi−conditional syntax is not limited to if statements and can be used any place where a conditional statement is required (including while and for loops). John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

Multi−conditional 'if' statements

25

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/08/23/php_foundations.html See this if you're having trouble printing code examples

Control Structures Revisited 08/23/2001 Today we'll revisit our discussion of control structures with the introduction of three new ones: do...while(), if....elseif, and the switch statement. Last time we discussed control structures we introduced the standard if() statement, the while() statement as well as the for() statement. Today we'll introduce two new variations of these control structures as well as introduce a completely new structure switch() and explain the similarities between it and the other structures.

The 'if' statement revisited The if statement was the first, and most important, control structure we learned. We learned how to use it to create conditional−executing code and how we could use its companion, the else statement, to guarantee that one part or the other would always be executed. Today we'll introduce briefly a new type of if structure used when multiple conditional checks are needed as well as a rather strange−looking conditional structure called the "conditional assignment" operator. Let's take a look at an example: $bar) { echo "$foo is greater than $bar"; } else { if($foo == $bar) { echo "$foo is equal to $bar"; } else { echo "$foo is less than $bar"; } } ?>

By now I would hope that the above code is easy to understand. Basically all we are doing is showing the relationship between two integers $foo and $bar and outputting that

Control Structures Revisited

26

O'Reilly Network: An Introduction to PHP Related Reading

PHP Pocket Reference By Rasmus Lerdorf Table of Contents Sample Section Full Description Read Online −− Safari

relationship to the browser. Although effective, the above set of control structures is very messy and could easily become a nightmare. It is for this reason that PHP has provided us with a different type of else statement called elseif. Its use is identical to a normal if statement except instead of using the else statement we substitute the elseif statement and provide another conditional. The formal syntax for the statement is as follows: If() { ... } [else[if()] { ... } [else { ... } ] ] When used in practice its primary purpose is to clean up our scripts and make them easier to understand rather than providing any real extra benefits. For an example, we'll rewrite our relationship example to use the new elseif statement: $bar) { echo "$foo is greater than $bar"; } elseif($foo == $bar) { echo "$foo is equal to $bar"; } else { echo "$foo is less than $bar"; } ?>

This script will function identically to our original version with the added bonus of removing the need to embed a second if statement within the else of another. There is no limit to how many elseif statements can be "chained" together within a single if conditional statement but any more than two and it is recommended that the switch() statement (that we'll cover later in today's article) be used.

The conditional assignment operator Consider the following conditional if statement:
The conditional assignment operator

27

O'Reilly Network: An Introduction to PHP $bar = 10; if($foo > $bar) { $foobar = true; } else { $foobar = false; } ?>

Often times it is necessary for a developer to assign the value of a variable depending on the evaluation of a conditional between two others. In this case, we are assigning a boolean value of true or false to the variable $foobar, depending of course on the outcome of the conditional $foo > $bar. As with our first example during our discussion of the elseif statement, the above will work as expected but is rather sloppy. Today we'll introduce a new type of syntax available in PHP that acts both as a conditional control structure and as an operator all at the same time. This control structure is called (for obvious reasons) the conditional assignment operator. The syntax for this new operator/control structure is as follows: $var = () ? <true value> : ; Although it looks somewhat strange, it functions exactly as the example just provided. The variable $var is assigned a value dependent on the conditions. If the conditions are "true," the true value will be assigned to $var and conversely if "false," the false value will be assigned. For a better illustration of this, we'll rewrite our example to use this new syntax: $bar) ? true : false; ?>

As we stated, the above example functions exactly as our previous one and will produce the same result. It is strongly recommended that a conditional assignment operator is used instead of an if statement when attempting to assign a variable either one variable or another. However, for the sake of readability this operator should not be used in the following manner: $bar) ? ($boolean) ? true : false : false; ?>

Where $foobar will only be assigned "true" if $foo is greater than $bar, and $boolean has a value of "true." A better way to write such a conditonal would be: $bar) &$boolean) ? true : false; ?> Or use the standard if conditional structure.

The conditional assignment operator

28

O'Reilly Network: An Introduction to PHP

A new look at the 'while' statement Now that we have covered both elseif and the conditonal assignment operator, we'll quickly take a look at a different flavor of the while statement: the do...while(). The do...while statement is nearly identical in syntax and behavior to a standard while statement with to differences. The first difference is in its syntax, the second is its functionality. The syntax for a do...while statement is: do { ... } while(
The real use (and difference) in a do...while statement as opposed to a standard while statement is how many times the code contained within it is guaranteed to execute. In a standard while statement, in theory the code contained within it could never be executed (the conditions required was never achieved). In a do while, the code contained within it will execute at least once (or more depending again on the conditions of the while). Below is an example of using a do...while statement to generate a random number greater than 100:

The result will be a value $myval that will always be above 100.

The 'switch' control structure To wrap up our continued discussion of control structures, we'll introduce a very useful alternative to use the if statement: the switch statement. switch statements are unique to any other control structure we have seen thus far, but in essence provide the same functionality as a conditional if statement. For example: Let's assume you would like to develop a script that would process commands from a menu. For argument's sake we'll assume the following menu items: Home Links E−mail Us In order to make development easier, we'll also assign special one−word identification codes to each of the three menu items. We'll call these home, links, and email respectively. Now that we have our menu options, and the identification codes assigned to each of them, it is time to write the logic that will determine which option the user selected. When the user clicks on one of our options, we'll send to PHP a variable $menu containing the identification string. So, all we have to do now is check the value of $menu to determine what option the user clicked on. There are a few methods a developer can use to accomplish such a task, such as the use of if...elseif, in code such a method would resemble the following:
A new look at the 'while' statement

29

O'Reilly Network: An Introduction to PHP echo "You clicked links"; } elseif($menu == "email") { echo "You clicked e−mail"; } else { echo "I don't know what you clicked"; } ?>

Unfortunately, code such as this tends to get confusing and out of hand rather quickly. It is for circumstances such as this that the switch statement was developed.

How the 'switch' statement works The switch statement could be visually represented as a dial with a number of positions on it. These positions are called "cases." When this imaginary dial is "switched" to one of the positions, a particular piece of code is executed that is associated with that dial. With that in mind, let's examine the syntax of a switch statement: Switch() { [case :] [case :] ... [default:] }

Looking at the above switch syntax we can see that the statement itself is variable and then within the code block is contained any number of case statements (each requiring a constant value) followed by an optional default case. So how does it work? When a switch statement is executed, it takes the variable passed to it (such as our $menu) and the compares it against each of the case statement values. In the event that the case statement value matches the value of the variable, the code below the case statement is executed. Optionally, you can also provide a default case to be executed in the event that none of the defined cases matches the provided variable. But, before we can continue and look at it in action we need to introduce a special companion statement to the switch control structure: the break statement.

Using the 'break' statement When a switch statement matches a particular case, as we stated before, the code directly below it is executed. However, PHP will not stop executing code inside of a switch when it encounters another case statement. Rather, it will ignore all further case statements and execute all of the code below the original match. For example:
How the 'switch' statement works

30

O'Reilly Network: An Introduction to PHP ?>

When the above code is executed, instead of the output simply being: You clicked links It will output: You clicked links You clicked e−mail I don't know what you clicked Although the break statement is most commonly found within a switch statement, it can be used in any code block to cancel execution of any further code within that block. Therefore it can be used to escape out of for loops, while loops, or even if statements. Because PHP was not told to stop executing the code, it continued straight through the entire switch statement and disregarded all further cases. Also note that PHP did not execute the "home" case since it was before the matching case "links." Sometimes, such behavior is beneficial, but in a scenario such as ours we would like to know exactly which case was selected and what menu option was clicked. By using the break statement we can command PHP to stop executing the code and leave the command block as demonstrated below:

With the use of the break statement, PHP will only execute the code between the different cases and our output will be as expected. John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. How the 'switch' statement works

31

O'Reilly Network: An Introduction to PHP Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

How the 'switch' statement works

32

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/05/03/php_foundations.html See this if you're having trouble printing code examples

Embedding PHP in HTML 05/03/2001 Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Introduction to PHP Objects, Part 1 Today we will discuss how to use special syntax to apply conditionals and loops.

Embedding PHP in regular HTML If you have been paying attention to our earlier articles, you hopefully have picked up on how PHP can be embedded into a regular HTML document. For example, we should already know that the following is an example of how PHP is embedded: My first PHP Page This is normal HTML code

Embedding PHP in HTML

33

O'Reilly Network: An Introduction to PHP Back into normal HTML

Further, we also learned how we could quickly output variables from PHP code without all of the hassle of an echo statement by doing the following:

Today, we will extend our knowledge of embedded PHP by discussing how PHP can be used to control the flow of a web page through conditionals or repetition−control structures.

How it works As mentioned in earlier articles, PHP will only process things that are enclosed within one of its valid code blocks (such as ). Because of this, PHP effectively ignores everything that it was not specifically told to process and can be used to our advantage. For example, what will the output from the following be? $var = 10;
The variable $var has a value of:


Is this a valid script? Yes, the output would be the following: $var = 10; The variable $var has a value of: 5

Notice that with the second assignment of $var, when we attempt to change the value from 5 to 10, it has no effect because it is not enclosed within valid PHP code−block syntax. So, instead of being processed, it is simply displayed to the web browser.

Embedded conditionals What if we wanted to display HTML only under specific conditions? For example, we only want PHP to display a navigation menu if the user is validated −− how could we do this? Using what we already know, we could simply put all the code for the HTML menu within echo statements (paying careful attention to add a backslash any time we need to output a quote for our HTML to the web browser) but this method can quickly become cumbersome and difficult to follow. Instead, to deal with situations like this, we will introduce a new flavor of our code−block syntax: ... HTML CODE ...

How it works

34

O'Reilly Network: An Introduction to PHP Although this may be confusing, remember how PHP will process this code. To start, it will evaluate the first line of a normal if statement and then begin a code block. Then, we turn off PHP parser and jump into normal HTML code (all of which PHP will simply output to the browser and ignore) until, finally, we return to PHP code and close our if statement. The result of this technique is a way for us to control regular and standard HTML with nearly no intrusion by PHP into the syntax. Although the above example works, a special syntax is provided for instances where PHP is being used simply to control the output of standard HTML code: ... HTML CODE ...

This syntax is identical in function to the original example provided.

Other valid embedded syntax Beyond simple if statements, most control structures provide an alternative syntax that allows us to embed PHP code within standard HTML quickly and easily. For example, below are definitions for our repetition statements while and for (starting with while): ... HTML CODE ...

And an identical syntax for an embedded for loop: ... HTML CODE ...

Embedded code in action Now that we have a feel of the syntax behind embedded control structures, let's look at a likely situation where our new knowledge could be put to use. What if we wanted to list, in an HTML table, all the numbers between 1 and 7 and determine under what circumstances our friend Billy could purchase a candy bar? Before we begin, we should get an idea of exactly how our HTML table should be constructed. For our purposes, we will be creating a table of the following form: 1

2

3

4

5

6

7

no no no no yes yes yes Now, let's take a loop at the HTML behind this table:

Other valid embedded syntax

35

O'Reilly Network: An Introduction to PHP
1 2 3 4 5 6 7
no no no no no yes yes yes


Notice that, when dealing with static HTML we have no flexibility whatsoever to alter the content of the table without manually changing it. What if we wanted to show a table of all the possibilities from 1 to 100? Again, accomplishing such a task by hand is a waste of time. However, with PHP, we can find a solution to our dilemma quickly and easily:
= 5) { echo "yes"; } else { echo "no"; } ?>


What have we done? Looking at this example, we start by simply outputting the basic HTML code to construct the web page and begin a table. Then, we use PHP to start a for loop to count from 1 to 7. Within this loop, we display the HTML code to first start a table cell, then display the variable we are counting with ($L) and finally the HTML to close the table cell. Once this has been completed, we close our row and start a new row and repeat the same looping process. This time, however, instead of simply outputting the looped variable, we use a conditional statement to determine if it is greater than or equal to the value 5 in which case we output "yes" or "no" depending on the Other valid embedded syntax

36

O'Reilly Network: An Introduction to PHP value of $L. Finally, we finish the HTML for our table and web page and the script ends. The result? Exactly the same static HTML page as we originally constructed except now we have the flexibility to examine any range with no extra effort. It is recommended that you play around and get very familiar with this syntax because it will be used quite often in future articles and in everyday practice. John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

Other valid embedded syntax

37

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/06/07/php_foundations.html See this if you're having trouble printing code examples

Arrays in PHP: Part 1 06/07/2001 This article will introduce the PHP array data type and discuss the fundamentals of working with arrays.

What exactly is an array? An array is a variable type in PHP that allows the programmer to associate one value directly to another value or simply take a set of data and organize it into a list format (much like a table). It can be used in many ways to store and organize data quickly and efficiently. It is one of the more useful data types available to any programming language. Let's say you are a developer who would like to find a way to store your favorite web site addresses using PHP. One highly discouraged method of doing so would be something like the following:

Did you experience any trouble with when first using arrays in PHP? Tell us about it. Post your comments Also in PHP Foundations: Working with Files in PHP

Arrays in PHP: Part 1

38

O'Reilly Network: An Introduction to PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Introduction to PHP Objects, Part 1 Effective, but such a method is hardly efficient. In situations like this, an array proves useful. The syntax of an array variable is almost identical to the syntax of any other variable in PHP. It follows the same rules regarding variable names, and in many circumstances can be referenced in the same way as any other variable. There are, however, distinct differences in how the data within an array is accessed and how an array variable is created. We'll discuss how to create an array variable first. When creating an array variable, there are two separate ways to declare it. The first should be used when the data the array will be storing can be hard−coded into the script (static data) and the second is used in circumstances when the data is read or generated during the execution of the script. It's up to you, the developer, to determine what format is right for you. With that in mind, let's take our above example and convert the data into an array format.

Using array() to construct a static array Array() is one of the methods PHP provides to create and populate an array with data. It is a PHP statement that takes your input and returns an array variable containing that input. Although the general format never changes, there is much more to this statement that we'll be covering in our next issue. For now, let's take a look at the general syntax of the array() statement: Array array([index]=>[value], [index2]=>[value], ...);

where for the purpose of this article index represents any integer and value represents any data type, variable or otherwise, in PHP. Remember this is a very limited look at the array() statement. In the next article, we'll return to this declaration to show you new and more useful ways to use this statement for complex data storage. It's also important to note that arrays in theory have no size limits imposed on them. Rather, they are limited by the storage capacity of the server running the script. Now that we have an idea of what an array() statement looks like, let's look at how our earlier example can be stored as an array: "http://www.onlamp.com", 1=>"http://www.oreilly.com", 2=>$site3); ?>

The result is a single variable, $mysites, that contains an indexed list of all three web sites from our earlier example. Notice that the third entry in our array (index #2) was assigned its value from the $site3 value. Therefore, the actual value stored at index #2 will be http://www.coggeshall.org. Now that we Using array() to construct a static array

39

O'Reilly Network: An Introduction to PHP know how to construct a basic array, how can we access its values?

Accessing array data Now that we've constructed our array, we'll discuss how we can retrieve our data from the array. To retrieve a specific value from our array, we need to reference the array variable and provide the specific index of the value we would like to retrieve. Let's say we wanted to access the third value (index #2) in our array, and echo it to the screen −− here's how we would do it:

Notice that this looks very similar to the echoing of any variable to the browser except when dealing with an array, we append brackets ( '[' and ']' ) to the end of the variable and reference the index of the value we would like to retrieve between them. We could access the first two values in our array just as easily by replacing the value "2" with 0 or 1.

Constructing an array dynamically When the data to be stored in an array is not known at the time the script executes, we'll need to construct the array dynamically. This would be rather inefficient and difficult to do using the array() statement. Instead, PHP has provided us a number of what I consider "informal" means of constructing arrays and populating the data. The first method is very similar to assigning any other variable in PHP and incorporates the array−reference syntax we outlined above. Say you would like to create a new entry in our previously created array of web sites. This entry you would like to have an index of "3" and a value of "http://www.php.net". You could append the existing array in the following fashion:

Now $mysites contains all three of the previously stored values plus the new fourth value you just added. Using this method of assignment, you can create new records or modify existing records with ease. Further, we can omit the actual index value and PHP will automatically assume the next sequential index value as illustrated in the next example:

The above will automatically store the web site at index #5.

Final notes Although we have only touched upon the power of arrays in PHP, already you have learned a very useful and powerful tool to assist you when developing PHP scripts. In the next column in this series, I'll discuss more advanced techniques such as associative (or hash) arrays as well as a new control structure that will help you traverse arrays quickly and painlessly. See you then! John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience.

Accessing array data

40

O'Reilly Network: An Introduction to PHP Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

Accessing array data

41

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/06/21/php_foundations.html See this if you're having trouble printing code examples

Arrays in PHP: Part 2 06/21/2001 Today we'll continue our discussion of arrays in PHP including the use of associative and multidimensional arrays. In my last article, we introduced a new array data type in PHP and covered its fundamentals. Today we'll dive deeper into arrays and introduce a type of array called an associative array and a more complex type of array −− the multidimensional array.

Associative arrays When we last discussed arrays, we described how arrays could be used and only deal with indexes based on integer numbers (1,2,3,etc). This week we'll introduce another type of array −− the associative arrays. Associative arrays are identical to any other type of array with one major difference −− their index values. In Associative arrays index values are not limited to simple integer values but can also be strings. For example, in an associative array the index "foo" can be used to store the value "bar". Thankfully, declaring and working with Associative arrays is identical to working with any other type of array. Here's an example: "bar"); $myarray_2["foo"] = "bar"; ?>

As you can see, working with associative arrays and integer indexed arrays is nearly identical. But how can we use associative arrays to our advantage? With such flexibility, we are able to assign any string (such as a name) with any other string or data type (such as a phone number or e−mail address). Another example would be assigning meaningless error messages generated by your web site to a more useful description. These are just two examples of the usefulness of associative arrays. Next, we'll discuss ways to embed arrays within other arrays to create what is called a multidimensional array.

Multidimensional arrays As we just stated, a multidimensional array is an array that contains at least one other array as the value of one of the indexes. An example of a multidimensional array would be an array $foo that has values for the indexes 1 through 5 with index value 2 containing another array. Creating and working with multidimensional Arrays in PHP: Part 2

42

O'Reilly Network: An Introduction to PHP arrays can be done a number of ways −− all of which we introduced in part 1 of this series. For example, in part 1 we discussed how to create a single−dimensional array using the array statement as follows: "abc", 1=>"def", 2=>"ghi"); ?>

Where the three indexes 0,1, and 2 are associated with different letters in the alphabet. In a multidimensional array, we can simply replace one of those associations with one that points to an array rather than a string constant. For example: "[email protected]", "dan"=>"[email protected]", "rachel"=>"[email protected]"); $foo = array(0=>"abc", 1=>$emails, 2=>"ghi"); ?>

As you can see, we have replaced index 1 in our $foo array with the variable $emails (also an array) and therefore creating a multidimensional array. Also note that we could have simply appended $foo automatically using the syntax we introduced in part 1 of the series:
$foo[] = $emails; ?>

Using the above would have created a new integer index 3 and associated with it the array $emails. Once we have created this association, we can add a whole new index to our $emails array that is embedded within $foo by the following syntax:
Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Introduction to PHP Objects, Part 1

Arrays in PHP: Part 2

43

O'Reilly Network: An Introduction to PHP Because index 3 of $foo is an array, we can reference that array by appending an additional set of brackets to the $foo variable. In the above example, the result would be a fourth entry with the index value of "steve" and data value of "[email protected]" being created in the array located at the 3rd index of the array $foo. It's a little confusing, but the best way to look at it is to remember that $foo[3] is really no different than $foo_3 (a normal variable name) in practice. When you reference an index of an array directly, the rest of the contents of the array are inconsequential and is best to disregard when trying to visualize complex multidimensional arrays.

More on working with and getting data from arrays To wrap up our two−part series on arrays, we'll briefly touch on some functions that will help you work with arrays (they will be discussed further in future issues), and introduce a new control structure that will greatly enhance the power of arrays in PHP. We'll start with some useful functions available to PHP developers to help them gather information and then introduce our new control structure (foreach). As we already mentioned, PHP has a wealth of pre−programmed functions for manipulating, analyzing, and processing arrays built into the language. For a complete list of these functions, please visit the PHP web manual reference for arrays. Almost all of them are very useful under the right circumstances so we'll only discuss the ones here that are necessary for just about any application of arrays in PHP. These functions are: is_array(), in_array(), and count().

Useful array functions Here are some useful functions to get you started working with arrays: • is_array($val) −− This is useful for testing if a variable is actually an array or not. It will return the value of "true" if the passed value is an array, "false" if it is not • in_array($needle, $haystack, $strict) −− a useful function to check for the existence of a value $needle in array $haystack. The third parameter $strict, when set to true, will also ensure that the value stored in $haystack is the same type as the search value $needle. The default value for the $strict parameter is false. • count($val) −− This returns the number of elements contained within an array. Note that in the event that $val is not a valid PHP variable, it will return a value of "0" instead of causing an error. It is recommended that is_array() be called prior to count() to ensure that the return value reflects the true nature of the variable being checked. For full documentation on these functions and examples of their use, please consult the PHP manual.

A new control structure: foreach Of all of the control structures available to developers in PHP, foreach is the only one specifically for use with arrays. In functionality, it is very similar to the for statement but doesn't look much like one in syntax. Its purpose is to provide a quick and easy way for developers to traverse the contents of an array (both integer indexed and associative) and process each element within the array. For example, let's say you have an integer−indexed array with an unknown number of elements that you would like to print the values for. This can be accomplished of course through the use of the for statement and our newly−found count() statement as shown below:
More on working with and getting data from arrays

44

O'Reilly Network: An Introduction to PHP echo $myarray[$i]; } ?>

There is nothing wrong with this style. However, what if the array was an associative array rather than integer−based? In such circumstances, complex while statements coupled with at least two more functions could produce the same results however we have a better solution: the foreach statement. The syntax for the foreach statement is as follows: foreach($array_val as [$key_val =>] $value) { ... }

It also has a syntax simliar to the for() endfor; syntax: foreach($array_val as [$key_val =>] $value): ... endforeach;

where $array_val is the array, $key_val is the variable assigned to store the current index, and $value stores the actual value associated with that index.

How it works Let's consider the following two samples of the foreach statement: "bar", 0=>5, "mynumber"=>12e3); foreach($myarray as $value) { echo "The value is $value
"; } echo "
"; foreach($myarray as $key=>$value) { echo "The value of index $key is $value
"; } ?>

In this code fragment, we create a simple array $myarray that has three values in it. The first is a string−based key "foo" with a value of "bar", the second is a integer−based key of 0 with a value of 5, and the third is a string−based key of "mynumber" with a value of "12e3" (or 12,000 in standard notation). We then use both syntaxes of the foreach statement and echo the results. When this script is executed, we'll get the following output: The The The The The The

value value value value value value

is is is of of of

bar 5 12000 index foo is bar index 0 is 5 index mynumber is 12000

When we compare the two foreach statement outputs, we can see that both of them traversed the entire array and stored the value stored at each index of the array in the variable $value which we then output to the screen. How it works

45

O'Reilly Network: An Introduction to PHP In the second foreach statement however, we specified a variable to be used to store the value of the index as well as the value at that index. The result was we were able to not only traverse the array for all of its values, but also retrieve and maintain the association between the indexes of those values. This is a very powerful and useful tool when dealing with arrays that will allow you to quickly and easily process each individual item within any type of array regardless of its type of index. It is strongly recommended that the foreach statement be used in all array traversals (instead of a for loop). Note: Although we used the values $key and $value in our foreach example, the variable names themselves can be any valid variable name within PHP (provided of course that it is not being used elsewhere in your script). John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

How it works

46

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/07/12/php_foundations.html See this if you're having trouble printing code examples

An Introduction to Functions, Part 1 07/12/2001 Today we'll introduce the function declaration, how it works, and how it can be used to create your own custom functions in PHP 4. What are functions? A function is basically a compartmentalized PHP script designed to accomplish a single task (usually a task that will need to be accomplished multiple times). Furthermore, code contained within functions is ignored until the function is called from another part in the script. We've already worked with some functions such as the count() function which returns the number of elements within an array. Today we'll introduce the syntax of a function in PHP and use what we have already learned to demonstrate how functions can be used to save time and effort.

Declaring your functions Creating a custom function in your scripts is a fairly straightforward concept. All functions in PHP begin with the keyword function followed by the function name. This function name must adhere to the same criteria as variables except they do not begin with $ character as other PHP variables do. Directly after the function name follows a set of parentheses containing the parameters to be passed. Before we discuss parameters, let's examine the formal declaration of a function: function

([$var1 [= constant]], [$var2 [= constant]], ...) {

}

where name represents the function name, and between the parentheses is contained an optional set of variable parameters to be passed to the function. Because these parameters are optional, we'll discuss functions without them first.

Our first function Now that we have an idea of what goes into the function, let's create our first basic function and demonstrate how to call the function from your script. In our function, we'll echo the string "Hello, PHP Functions!" 10 times and then show how functions affect the way the PHP code is interpreted:

An Introduction to Functions, Part 1

47

O'Reilly Network: An Introduction to PHP "; } } echo "This is before the function is called
"; myfunction(); echo "This is after the function has been called"; echo "
"; ?>

The output to the browser when this script is executed is: This is before the function is called Hello, PHP Functions! ... (nine more iterations) This is after the function has been called

Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References

Passing parameters to functions Now that we've covered functions that contain no parameters, we'll discuss what it means to pass parameters to a function in PHP and go into the details of how to do it from within your scripts. A function parameter is nothing more than a piece of data that the function requires to execute. For instance, the function count() requires that an array is passed to it −− if not, what could it count? As per our formal definition, function parameters are represented by variable names located within the parentheses of the function definition. For instance, the following is an example of our previous function with one distinct difference −− we now will be able to specify how many times our message will be displayed and the text of the message from outside of the function:

"; } } echo "Printing the message 5 times....
"; myfunction(5, "This is the message"); ?>

Passing parameters to functions

48

O'Reilly Network: An Introduction to PHP

Default parameter values Normally, when parameters are declared as part of the function declaration they become a required part of the syntax when the function is called. That is, you can not call myfunction() with no parameters if the function itself requires them. Fortunately, PHP supports the ability to assign default values to function parameters. For example, we can rewrite our function a third time to include a default parameter for the message: "; } } echo "Displaying the default message 5 times
"; myfunction(5); echo "Displaying a custom message 6 times
"; myfunction(6, "My custom message"); ?>

Through this method, you can create more versatile functions that allow you to make assumptions on the data being passed to the function without sacrificing flexibility.

Final notes With that, we'll conclude today's introduction to functions. Although we have covered the majority of the topic of functions in PHP, there are still more topics to be addressed in a future article. Fortunately, our introduction should be more than enough to get started using this most powerful and time−saving feature of PHP. Happy coding! John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

Default parameter values

49

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/08/09/php_foundations.html See this if you're having trouble printing code examples

Introduction to Functions: Part 2 08/09/2001 Today we'll revisit our discussion of functions and introduce several new topics, including scope, static variables, and return values. The last time we spoke about functions, we took a fairly basic look at how they work and how they can be used in your scripts. This included declaring functions both with and without parameters, as well as how to declare default values for any parameters that the function may require. Today we'll extend on that discussion and explain many advanced topics dealing with functions. To begin, we'll start with the concept of function scope and how it can affect you when developing your own functions.

Variable Scope For those of you with programming experience, the term "scope" may already be familiar to you. For those who are not familiar with the term "scope," it refers to the concept that a variable inside of a function cannot be inherently accessed by parts of the script which reside outside of that function. To better illustrate this, let's take a look at a bit of color−coded code and an associated diagram:

When this code is executed, what will the output be? A reasonable answer to this question would be to say that we would echo the value of $foo twice, and hence the string "Hello" would be outputted twice to the browser −− but this is not the case. Although the variable $foo will be outputted twice to the browser, the result will only be a single "Hello." The reason this occurs is because the variable $foo inside of myfunction() is a completely different variable from the one outside of the function. That is to say, the "scope" of $foo within myfunction() is local to that function and separate from any other variables named $foo that reside outside of that function. This separation of same−name variables inside and outside a function is an important characteristic trait of PHP scripts. In order to access the variable $foo from within Introduction to Functions: Part 2

50

O'Reilly Network: An Introduction to PHP myfunction(), we'll need to introduce a new statement: global.

The Global Statement The global statement's purpose is to allow a developer to access a variable outside the scope of a given function. The syntax for global is as follows: global $var1, $var2, $var3, .... ;

Where $var1, $var2, etc. represent the different variables you which to access from within your function. To demonstrate how global works, we'll return to our example above and use the global statement to fix our bug and make the script output the contents of $foo twice:

Because of the use of the global statement in myfunction(), we have instructed PHP to treat all references to the variable $foo inside of the function the same as it would as if it was not a part of the function at all and within the same scope as the rest of the script. The result is the variable $foo will be outputted to the browser twice, once in the normal part of the script and then again in the function that the script calls.

Persistent Function Variables Related Reading

PHP Pocket Reference By Rasmus Lerdorf Table of Contents Sample Section Full Description Read Online −− Safari Another interesting behavior when dealing with functions in PHP is the concept of persistent variables. Under normal circumstances, the life of a variable within a PHP function starts when the variable is first initialized within the function (either as a parameter or a declared variable) and ends when the function has been executed and the script continues. Under some circumstances, it would be beneficial if PHP could remember certain variables stored within a function to be used next time the function is called. For example, what if we wanted to make a function that remembered how many times it had been called throughout the script? We'll show you how you can use static variables to accomplish this task.

The Global Statement

51

O'Reilly Network: An Introduction to PHP

The Static Keyword The static keyword is used when declaring a variable in PHP. It's purpose is to inform PHP that this variable should not be destroyed when the a given function executes, but rather its value should be saved for the next time it is needed. The syntax is: static [var] $variable [= ]

In a script without functions the static keyword serves no purpose, since regardless of what type of variable it is, PHP will destroy it when the script is finished executing. However, when dealing with functions it can be used to retain certain desired variables within that function for the life of the script's execution. To illustrate this we'll now use the static keyword to count how many times a given function has been called: 5; $i++) { staticfunction(); } ?>

Under normal circumstances, this function would execute five times and each time the output would be: Function executed 1 time(s)

Because each time the function is called the variable $count would be created with the value of 0 and destroyed at the end of the function. Instead, because we did use the keyword static to define our variable, it is initialized a single time to the value of 0 and saved at the end of the function to be used next time the function is called. The result of calling the function five times under this circumstance will be: Function Function Function Function Function

executed executed executed executed executed

1 2 3 4 5

time(s) time(s) time(s) time(s) time(s)

Returning Values From Functions As you may or may not have noticed, variables are often assigned values based on the execution of a function. For example, here we are using the built−in function count() to assign the variable $items the number of elements in array $foo:

Until now, all of the functions we have discussed are unable to function in this manner. This procedure is called "returning" from a function and, appropriately enough, we can do so with the use of the return statement.

The Static Keyword

52

O'Reilly Network: An Introduction to PHP

The Return Statement return statements are used when you would like to be able to assign a variable's value based on the results of the execution of a particular function, as we did with the count() function above. Use of the return statement is very straightforward, so we'll jump right into the formal definition and a small piece of example code: return ;

Where value represents any value available in PHP, including an array. For example, the following is used to assign the variable $foo with "Yes" or "No," depending on the parameters passed the to function: $val2) { return "Yes"; } else { return "No"; } ?> $foo = greaterthan(5, 2); echo "Is 5 greater than 2? −− $foo!"; ?>

The result of the above script will be: Is 5 greater than 2? −− Yes!

Final Notes And so concludes our introduction to functions. With what we have learned in this series, we should now be able to work with functions in confidence and use them when appropriate in our scripts. However, the discussion is far from over! Come back soon for a continuation of this series to learn about advanced function topics and how they can be used to improve the way your scripts function. Happy coding! John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

The Return Statement

53

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2001/05/17/php_foundations.html See this if you're having trouble printing code examples

Advanced PHP Variables and Functions 05/17/2001 Today we'll discuss an advanced function concept called variable−length argument lists, and explain how to use dynamic function and variable names in PHP.

Variable−length argument lists Until now, we have looked at parameters that are passed to custom functions to be statically defined (meaning once you decide on a set of parameters you are stuck with them until you change the declaration). Today, we'll discuss how you can create functions that define no parameters yet still function as expected when any number of parameters are passed to them. This concept of variable−length argument lists is made possible by a small family of built−in PHP functions: func_num_args(), func_get_arg(), and func_get_args().

The func_* function family The func_* family of functions is a set of functions designed to run inside another function. Their purpose is to retrieve information regarding the arguments passed to the function in question. Because PHP allows you to pass parameters to functions that take no parameters in their definition, these functions can be used to create functions that take an unlimited number of parameters. For instance, consider the following snippet of code: "; } } dynamic_args("a", "b", "c", "d", "e"); ?>

Compared to earlier examples of functions, the example above seems incorrect because we are defining a function that takes no parameters yet we are calling the function and passing five parameters to it. As stated Advanced PHP Variables and Functions

54

O'Reilly Network: An Introduction to PHP earlier, PHP will allow us to pass extra parameters to our functions without error −− our real interest is in the function itself. In the above function, we are using two of the func_* family commands to gather information regarding the parameters passed to dynamic_args(). First, we use func_num_args() to return the total number of arguments passed to dynamic_args(). In this case, the total number of parameters passed was five. Then, from within the for loop, we use the function func_get_args() and pass the index $i to it. When this is done, func_get_args() returns with the value of the parameter which equates to the index provided. This process continues until our for loop ends. The results of calling dynamic_args() with the parameters we specified would be the following output to the browser: Argument Argument Argument Argument Argument

0 1 2 3 4

= = = = =

a b c d e

As you can see, through the use of these very powerful functions available to us, we are able to create functions that can accept an unlimited number of parameters with ease. We can also use this method to create functions that require one parameter followed by an unlimited number of additional parameters as shown below:

In the above example, we define a function implode_str() that requires a single parameter $glue. Then, inside of our function we use the same function calls as we did in our earlier example to create a string $string based on the value of the extra arguments passed and the value of the $glue variable. Note that our for loop now starts off at 1 rather than 0. This is because we are declaring a single variable in our definition, so we will ignore it by only looking at variables passed after it that parameter. When the function is executed with the parameters above, its output will be: This−is−a−test. This is just one of the many ways to mix and match function definitions with the func_* family of functions to create variable−length argument lists.

Variable variables and function names Note: Variable functions and variables are a potential security risk if used improperly. Before using variable function calls or variables, it is important to consider possible security holes that could arise from malicious user input.

Variable variables and function names

55

O'Reilly Network: An Introduction to PHP Beyond dynamic parameters, PHP also supports the ability to call functions dynamically, as well as use variables dynamically. That is, we can write scripts that call functions and access variables without knowing the names of the functions or variables until the script starts executing. We'll start with how this can be accomplished with variables first, and then conclude with a similar syntax to be used for executing functions.

Variable variables It is possible to access a particular variable in PHP without even knowing its name until after the script starts executing. This is done through a special variable syntax that is defined as the following: ${} where the variable name is either a constant (such as "foo") or another variable containing a string representation of the name. Sound confusing? Why don't we look at some examples to help make things more clear: Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Introduction to PHP Objects, Part 1 "; $bar = "This is the variable bar
"; $foobar = "This is the variable foobar
"; $foo_name = "foo"; $bar_name = "bar"; echo echo echo echo echo

$foo; $bar; ${$foo_name}; ${$bar_name}; ${$foo_name.$bar_name};

?>

Above is what appears to be a fairly easy−to−understand script that simply echos different variables to the browser. However, the last three echo statements are referring to very strange looking variables. Consider the first of the last three echo statements. On this line, we are telling echo to print the variable whose name is contained within $foo_name. Because $foo_name's value is "foo", the echo statement will print the value of our PHP variable $foo to the browser. Although the second of the three is basically identical, the last statement is a little different. Here, we use the string concatenation operator '.' to combine the values of $foo_name and $bar_name to create the string "foobar" which we then use as the variable name for our last echo statement. The result of all of this is the following output:

Variable variables

56

O'Reilly Network: An Introduction to PHP This This This This This

is is is is is

the the the the the

variable variable variable variable variable

foo bar foo bar foobar

With this syntax, it is possible to write extremely complex scripts that are quite dynamic in nature with much less work then normally needed. Now that we have an idea on how to use variable variables, let's look at how to call functions based on the value of a variable.

Variable functions Variable functions work on the same principal as variable variables. Basically given a variable containing a string representing a function in PHP, you can call the function simply by appending parentheses and any parameters to the end of the variable. For instance: "; } $func_name = "myfunc"; $func_name("Hello, this is a test"); ?>

will call the function myfunc() and pass our message "Hello, this is a test" to it. We accomplish this task by calling the function through the use of the variable $func_name that contains the actual name of the function myfunc.

Dynamic function creation Beyond calling functions dynamically, it is also possible create functions dynamically. This can be done through the use of the create_function() function in PHP. The syntax of this function is as follows: string create_function(string args, string code);

When called, we pass to the function two parameters. The first, args, is a string that contains the code that would normally go between the parentheses of a function declaration. The second parameter code is a string representation of actual PHP code that consists of what normally would be the body of a given function. When the create_function() is called, it creates the function as specified and returns a variable containing the name of that function that you can then use to call the function. Let's take a look at an example:

Variable functions

57

O'Reilly Network: An Introduction to PHP In this example, we create two functions that are identical in output. In the first example, we declare prior to the script's execution and we name it my_normal_func(). In the second example, we create the function with a call to create_function(). When we execute the script, the function will be created and the name assigned to the function will be stored in the variable $func_name and will have the exact same code and parameters as the function we declared. This process can be useful in a number of circumstances (such as creating callback functions or data validation functions), and it is recommened that you read the manual entry on create_function() available on php.net for more information on how to use this function in everyday coding practice.

Final notes With PHP, it is possible to create extremely complex, nearly self−creating programs that produce excellent results with a minimal amount of development time. As with almost every powerful tool, improper and careless use of dynamic programming can result in serious security leaks. Never base dynamic code on direct input from the user without first checking to ensure it contains no harmful or malicious code before creating functions or executing commands (particularly dynamic ones) based on it. Until next time −− happy coding! John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

Final notes

58

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2002/06/20/php_foundations.html See this if you're having trouble printing code examples

Multiple File PHP Scripts

by John Coggeshall 06/20/2002 Although it's not ever truly necessary, many times it becomes very important to have the ability to separate PHP code into multiple files to ease organization and promote the idea of reusing common functions within your PHP scripts. Thankfully, PHP supports four different language constructs and functions to allow for the import of code from other files, which I will discuss now.

Including Code in Your PHP Script There are many ways to include code in PHP. Depending on your system's configuration, you can include files from both your local file system or even from remote servers that are configured to do so. There are many different tricks and useful ways to use this behavior in PHP and I'll try to cover most of them here. The most basic of all code imports in PHP can be done with the use of PHP's include() statement. The syntax for the include statement is as follows: include <path or URL to the file to include>

When an include statement is encountered by PHP, the PHP engine immediately stops parsing PHP code and attempts to import the code directly over the calling include statement. This means that whatever code is contained within the requested file will replace the include statement and will have available to it any variables that were defined, as well as be constrained to the same variable scope. Furthermore, any PHP code that is included must also be wrapped in standard PHP code tags such as .

Multiple File PHP Scripts

59

O'Reilly Network: An Introduction to PHP Related Reading Programming PHP By Rasmus Lerdorf, Kevin Tatroe Table of Contents Index Sample Chapter Read Online−−Safari

Here's an example. Below are two different files. The first file, myscript.php is the file that has been executed by PHP initially. The second file, included.php is another PHP script that is meant to be included: myscript.php '; ?>

included.php '; ?> >?php $testvar = true; ?<

In the above example (assuming, of course, the file included.php is in the same directory as myscript.php) the output will be: The value of the variable is: 0 The value of the variable is: 1 ... The value of the variable is: 9 $testvar is set

Notice that the $i variable was not defined anywhere in the included.php script where it is used; instead it has been automatically inherited from the calling script. Note: The above output is not in error. Because the above script uses single quotes instead of double quotes to check for the existence of $testvar in the final echo statement, it will be displayed to the client as is, and the output will reflect the string '$testvar' instead of the value contained within the PHP variable of the same name.

Multiple File PHP Scripts

60

O'Reilly Network: An Introduction to PHP

Returning Values At times, it may be beneficial to return a value from within the include statement back to the original calling script. To accomplish this, you may simply place a return statement within the include file but outside of any functions defined within the included file. The returned value will be the result value of the include statement that initiated the inclusion of the file, as shown below: myscript.php "; $returnval = include 'includeanother.inc'; echo "The file includeanother.inc returned a value of '$returnval'
"; ?>

includeme.inc

includeanother.inc "; ?>

The result of the above code executing would be: The file includeme.inc returned a value of 'testing' Hello, world! The file includeanother.inc returned a value of '1' Note that if the included file returns no value the include statement will return true upon success or false upon failure.

Ensuring Files Are Only Included Once In the above script, you'll notice that we used the include statement to include the same file over and over, each time producing a different result. Sometimes, such as when the file desired to be included as a function definition within it, it is important that the file be included once and only once. Although there are ways to ensure this with a standard include statement PHP provides the means to accomplish this very cleanly by using the statement include_once instead of simply include. The include_once statement behaves identically to its sister statement include with the single difference that PHP will not include the file multiple times. It is recommended that this version of the include statement be used in situations where included files contain function declarations or other code that should not be executed numerous times. Returning Values

61

O'Reilly Network: An Introduction to PHP

A Note on Errors Occurring with Include Files One important thing to note regarding the include and include_once statements is how PHP handles errors that occur either loading them, or during the process of executing the code within them. In the event of an error during an include statement's execution, PHP will generate a error of type E_NOTICE and continue execution of the script. How this error is presented to the user depends on the configuration settings of PHP. If the included file is critical to the script's operation, you'll need to use the require statement described below.

Forcing Files to Be Included As I've discussed, errors that occur during the inclusion or executions of included files using the include or include_once statements will cause the trigger of an E_NOTICE error and return false. Because this error is not considered fatal by PHP scripts, the desired file simply will not be included and script execution will continue. In situations where the code contained within the include file was required, this will produce unpredictable results. To combat this, PHP provides another similar way of including files: the require and require_once statements. In versions of PHP prior to 4.0.2, the require statement behaved differently than its counterpart include in both the way and at what time files were included. In versions of PHP above 4.0.2, require now behaves almost identically to include. The only difference is in what PHP does in case of an error. If an error occurs during the execution of a require or require_once statement, it will trigger a fatal error of type E_ERROR resulting in the entire script execution halting. This behavior is most desired when the included code is critical to the general function of the entire script, such as the setting of critical variables or the definition of functions that are used within the calling script. As with include_once, require_once will ensure that the requested file is included in the PHP script only once.

More to Come That's just about all there is to the process of including files in your PHP scripts! With this important facet of PHP out of the way, next time I'll be introducing object−oriented programming in PHP and how it can be used to save you time writing and reusing your code. John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Return to PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

A Note on Errors Occurring with Include Files

62

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2002/07/18/php_foundations.html See this if you're having trouble printing code examples

Introduction to PHP Objects, Part 1

by John Coggeshall 07/18/2002

Introduction Welcome back! Last time we met, I discussed with you the concept of using multiple files to store your PHP scripts. In today's column, I'll be introducing one of the more interesting and useful methods of writing PHP scripts −− the object−oriented method. Those of you who might have experience with an object−oriented programming language such as Java or even C++ will find themselves right at home with most of the concepts I'll begin outlining here. However, be warned −− PHP objects have a mixture of C++ and Java, making them a little different than what you might be used to. In any case, let's get started with the basics.

The What and Why of Objects For those of you without much experience in object oriented programming, you may be asking yourself, what exactly is an object and why is it useful? The best answer that I have heard describing an object is simply a "black box" that serves a function or functions. What is a "black box?" What I mean is that a "black box" is a chunk of code which is completely independent of any other code −− it takes in information, processes it, and returns a result. You, as the developer, do not need to know anything whatsoever regarding the internal workings of the code. Furthermore, objects are extendable, allowing developers to build off of already−existing code. I know all of the above might be a lot to take in at once (and we haven't even discussed everything yet). Don't worry! I'll be discussing more on the things I've touched on above in the future, when it'll make much more sense. Thankfully, there is a lot that can be understood just by being walked through the basic syntax, so let's take a look.

Introduction to PHP Objects, Part 1

63

O'Reilly Network: An Introduction to PHP Related Reading Programming PHP By Rasmus Lerdorf, Kevin Tatroe Table of Contents Index Sample Chapter Read Online−−Safari

Simple Class Syntax in PHP The basic syntax in PHP object−oriented programming is basically the same as in a language such as Java. Classes (the code that creates an "object") are defined by the class keyword. Here's an example of a class with nothing inside of it:

Member Variables and Creating an Instance Of course, a class that has nothing inside of it isn't useful. For a class to be of any use, we'll need to add some functions and member variables. Let's start by adding the variable $foo to our class, renaming the class to foo_object, and, just to make things interesting, let's also set the value of $foo to the string value bar:

Now that we have a class with something inside of it, how do we actually get at and work with this data? To create an object (also known as an instance of a class) you'll need to be introduced to another keyword −− the new keyword. Here's an example where we'll create a new object $myobject that is an instance of our example class foo_object:

Simple Class Syntax in PHP

64

O'Reilly Network: An Introduction to PHP When the PHP engine encounters this statement, it searches for a definition of the foo_object class. Since we have already defined it, the engine creates a working copy of this class and stores the reference to it in the variable $myobject. This means that through the variable $myobject, you can now access any variables or functions that existed within the definition of the foo_object class. For instance, if we wanted to work with the $foo variable inside of this particular instance of foo_object, we could do so as follows: foo = 5; // Echo the value of the $foo variable echo $myobject−>foo; // Prints '5' to the browser ?>

Member Functions and the $this Reference Variable Please note that, at least by convention, developers rarely access member variables directly. Rather, it is the job of the class to provide functions that modify any member variables that the developer may need to modify. With that said, let's create a new class, counter, that creates two member variables, $step and $count, and member functions to work with them. count; } function getstep() { return $this−>$step; } function changestep($newval) { if(is_integer($newval)) $this−>step = $newval; } function step() {

Member Functions and the $this Reference Variable

65

O'Reilly Network: An Introduction to PHP $this−>count += $this−>step; } function reset() { $this−>count = 0; $this−>step = 1; } } ?>

Now, let's take a look at what is really involved in the example above. First, we declare the two member variables $step and $count, which you have already seen in prior examples. Next, we begin the creation of five functions: getcount(), getstep(), changestep(), reset(), and step(). The code contained within these functions is very simple, but there is one thing that probably seems a bit alien −− the use of the seemingly−undeclared variable $this. The variable $this is available from anywhere within any PHP class and is created by PHP when an instance of the class is created. Basically, the $this variable is a reference to the created instance itself, just as $myobject was a reference to the foo_object class. As you can see through the use of the $this variable, you can access variables within an instance of a class, from within the instance itself. Now that we are dealing with functions, let's take the example class we have created above and put it to a semi−useful purpose. Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 2 Multiple File PHP Scripts reset(); $ticker−>changestep(2); while($ticker−>getcount() <= 20) {

Member Functions and the $this Reference Variable

66

O'Reilly Network: An Introduction to PHP echo "The value of the ticker is " . $ticker−>getcount()."
"; $ticker−>step(); } ?>

Can you follow the code above, looking at the class definition? First, we create an instance of the class and store a reference to it in the variable $ticker. Next, we call the member function reset(), which resets the counter to its original state and sets the step−count to 2 (meaning that it will count by twos). Then, we loop until the ticker has reached the value of 20. The result will be the following output: The value of the ticker is 0 The value of the ticker is 2 The value of the ticker is 4 ... The value of the ticker is 20

More to Come Now that I've covered the very basics of object−oriented programming in PHP, I suggest you work with them a bit and make sure you understand them completely before moving on! In my next column, I'll be discussing some more advanced topics, including object inheritance, special member functions, and more! John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Discuss this article in the O'Reilly Network PHP Forum. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

More to Come

67

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2002/08/01/php_foundations.html See this if you're having trouble printing code examples

Introduction to PHP Objects, Part 2

by John Coggeshall 08/01/2002

Introduction Welcome back! In my last column I introduced to you the concept of classes in PHP and provided you with some basic examples for writing your scripts in an object−oriented way. This week, I'll discuss the concept of objects in more detail, including some of the more powerful features (and the main reason to use objects) such as inheritance and using objects as data−storage containers. Let's get started.

Object Hierarchies One of the most powerful uses for objects and classes within PHP (as with any other programming language that supports objects) is the concept of an object hierarchy. Although it is sometimes difficult to apply, the principals are rather easy to explain. Let's say, for example, you are interested in writing a script to catalog types of cars. One approach, of course, would be to use arrays to store all the possible information that could exist. However, this will not work as well for situations where you would also like to store information unique to a specific type of car (such as the towing capacity of a truck). A more efficient and powerful method is to use objects, as I will show you below.

Extending Objects Before we can really discuss a good solution to the above cataloging problem, first we have to introduce the concept of class extending. Let's take a look at a quick example:

Introduction to PHP Objects, Part 2

68

O'Reilly Network: An Introduction to PHP Related Reading

Programming PHP By Rasmus Lerdorf, Kevin Tatroe Table of Contents Index Sample Chapter Read Online−−Safari id; } }; class car extends item { var $color; var $horsepower; function setColor($color) { $this−>color = $color; } function setHP($hp) { $this−>horsepower = $hp; } function getHP() { return $this−>horsepower; } function getColor() { return $this−>color; } }; ?>

In the above code, we have defined two classes. The first class, item, has a single member variable $id with a function used to retrieve it getID(). We could create an instance of this class, however, it wouldn't be very useful by itself. To make the creation of the item class useful we must look to the second class we defined: car. As you can see above, the car class has "extended" the item class declared above and has access to all of its functions and member variables. To illustrate this point, examine the following code:
Introduction to PHP Objects, Part 2

69

O'Reilly Network: An Introduction to PHP $mycar−>setColor("Blue"); $mycar−>setHP("406"); $mycar−>id = "myidentification"; echo "The ID of my car is: ".$mycar−>getID(); ?>

Considering only what we have learned so far in part one of this series, the first three lines of the above code should be fairly self−explanatory. However, looking at our original class definition for the car class, lines four and five seem to refer to variables and functions that are undefined in the class. Because our defined car class extends the item class (called the parent class), it has access to all of its member variables and functions, so the above code will work as expected.

Overloading Member Functions and Parent Referencing One of the most powerful features of object−oriented programming is the ability to overload a function defined within another class. For instance, adding the following to the class definition of car: function getID() { return "No ID Found"; }

Any references to the member function getID() from an instance of the car class will result in executing the function defined within the car class. Although useful, there may be times when the functionality of both the initiated object and its parent class is desired (for instance, when the parent class provides a basic functionality to be extended by a child class). To facilitate this, PHP provides the parent reference. Below is an example of the parent reference in action: Also in PHP Foundations: Working with Files in PHP Advanced PHP References PHP References Introduction to PHP Objects, Part 1 Multiple File PHP Scripts "; } }; class childclass extends parentclass { function foo() { echo "This is the child class
";

Overloading Member Functions and Parent Referencing

70

O'Reilly Network: An Introduction to PHP parent::foo(); } }; $myclass = new childclass(); $childclass−>foo(); ?>

Executing this script produces the following output: This is the child class This is the parent class

Object Serialization Along with the active functional aspects of objects in PHP, they can also be stored (in their current state) in a database or a file system through a process called serialization. This process is accomplished through the functions serialize() and unserialize(), which converts an instance of an object (or any variable) into a string that can be written to a file or stored within a database, as shown in the code below: a; } function addvar() { $this−>a++; } }; $bar = new foo(); echo "The value of the variable a is: ".$bar−>getvar()."
"; $bar−>addvar(); $str = serialize($bar); unset($bar); $foobar = unserialize($str); echo "The value of the variable a is: ".$foobar−>getvar()."
"; ?>

As the above code demonstrates, first we define and create an instance of the class foo (which we store in the variable $bar) and echo its variable to the browser. Then, we increment the variable in our $bar class and store the serialization string of $bar created by the serialize() function in the $str variable. At this point, note that the instance $bar has been completely destroyed. From this point, we recreate the object from its serialization string and store it into a new variable $foobar, effectively recreating the object from its original state before it was destroyed. Here's what the output will look like: The value of the variable a is: 1 The value of the variable a is: 2

Please note that, when an object is being recreated through a call to the unserialize() function, it is important that the class defining the instance of the object exist. For example, attempting to reconstruct the foo class above, without having the class definition for the foo class, results in an empty, useless class being created.

Object Serialization

71

O'Reilly Network: An Introduction to PHP

More to Come This concludes my discussion (at least for now) of using objects within PHP! I hope you now have a firm handle on how objects are handled within PHP, and that you also have some great tricks at your disposal to create reusable and storable PHP code. In my next article, I'll be tackling a whole new aspect of writing scripts in PHP when I discuss the closer thing that PHP has to a C−style pointer: References. John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter. oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

More to Come

72

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2002/08/15/php_foundations.html See this if you're having trouble printing code examples

PHP References

by John Coggeshall 08/16/2002 Welcome back. In my last article, I wrapped up my discussion of using objects in PHP. This week I'll be changing gears a little bit and discussing one of the more elusive aspects of PHP −− references. For those of you with a C programming background (although they are fundamentally different), references serve the same purpose as a C−style pointer. For those of you without programming experience in C, don't worry! I'll be covering everything you'll need to know today.

Basic References Explained Regardless of your background, the concept of a reference in PHP can be a bit difficult to grasp until properly explained. As I mentioned earlier, PHP references serve the same purpose as a memory pointer in a C−style language. For those of you who aren't familiar with C or similar languages, I'll explain further. As its name implies, a reference in PHP is a variable that "references" the contents of another variable. For instance, consider the following small piece of code: "; $foo++; $bar−−; } ?>

When the above code executes, what will be the result? You should have no problem seeing that as the loop cycles through, the result will be five lines of text, output to the client in the following fashion: The value of foo is: 5, and the value of bar is 5 The value of foo is: 6, and the value of bar is 4 .... The value of foo is: 10, and the value of bar is: 0

PHP References

73

O'Reilly Network: An Introduction to PHP The point is that the variables $foo and $bar are independent of each other, and each can be modified without any other variables being affected. PHP references allow the developer to tie two separate variables together, allowing you to modify both at once. Let's consider the following, slightly modified version of the above code: "; $foo++; $bar−−; } ?>

Notice that the second line in the above code has changed. Instead of simply assigning the value of $foo to the variable $bar, we now have used the =& operator to set the variable $bar as a reference to the variable $foo. What's the difference? Let's see when the code is again executed: The value of foo is: 5, and the value of bar is: 5 The value of foo is: 5, and the value of bar is: 5 .... The value of foo is: 5, and the value of bar is: 5

As you can see, neither variable seemed to move from its original value! Although you might at first consider this a bug, let's look at the code line−by−line. First we start by assigning the integer value 5 to the variable $foo. Next, we create a reference to the variable $foo and call it $bar. As we enter the for loop, we print the contents of both variables and as expected, both are equal to five. Then we increment the value of $foo, decrement the value of $bar, and repeat. But why did the values of $foo and $bar remain constant? In the first example, we took a value of 5 and assigned it to the variable $foo. Then, we created a second variable, $bar, and assigned it the same value as $foo. However, notice that a second variable $bar was created, and thereby is completely independent of the first. In contrast, the second example created a reference to $foo and called it $bar. When this is done, a second variable is not created, but rather a single variable is given another variable name, as shown below:

Figure 1: $foo and $bar as independent variables

Figure 2: $bar as a reference to the variable $foo As you can see by the above illustrations, PHP references allow you to work with the same physical data using different names. Looking back at the second example, you can now see that when the variable $foo was incremented, it indeed was assigned a value of 6. However, because $bar is a reference to the variable $foo, when it was decremented in the following line, $foo was again set to the value of 5. The result, of course, is that the script appeared to never change the value of the variables at all!

PHP References

74

O'Reilly Network: An Introduction to PHP Related Reading Programming PHP By Rasmus Lerdorf, Kevin Tatroe Table of Contents Index Sample Chapter Read Online−−Safari

References and Arrays Just like standard variables, references can also be used in conjunction with arrays. A PHP reference can occur for an entire array, or for a specific index. For instance, let's take a look at the script below that creates three different references to variables contained with an array: 'variable1', 1=>'variable2', 2=>'variable3'); $ref1 = &myarray; // Reference the entire Array $ref2 = &myarray[0]; // Reference to the first index $ref3 = &myarray[1]; // Reference to the second index ?>

Passing By Reference Beyond the use of references when working with standard variables, references can also be used in conjunction with function parameters. This ability proves especially useful when it would be desirable to return more than one result from a given function. For instance, let us assume that we would like to create a function called split_string() to cut a string in half. This function takes two parameters, a string and an integer, and returns two strings representing the two halves. Unfortunately, the nature of a function does not allow us to return two different variables, so another solution must be determined. One possibility would be to store the two halves of the result into an array and return an array of strings. For another solution, take a look at the following code:

In this solution, the split_string() function created takes not two, but four parameters. The first two parameters have already been described, while the second two parameters are actually references to the variables where the result will be stored. Also note that this function's return value is a boolean indicating the success of the function. This function is called as follows:
References and Arrays

75

O'Reilly Network: An Introduction to PHP echo "
"; } if(split_string($input_text, 10, &$first_half, &$second_half) == true) { echo "First segment of input: $first_half
"; echo "Second segment of input: $second_half
"; } ?>

This would produce an output as follows: Could not split input, cut−point is entire string! First segment of input: abcdefghij Second segment of input: klmnopqrstuvwxyz

As you can see, because the function utilized reference−passing, we were able to successfully return two separate parameters from the function with ease, and left the return value to be used for error checking. Although not always the best course of action, the ability to pass parameters by reference provides a great deal of flexibility to the developer (especially when used in the design of advanced algorithms).

More References Later That's all the time this week for our discussion of references! In my next article I will continue my discussion of references by explaining the more advanced techniques of using references, including how references are implemented in objects and how to return a reference as the direct result of a function (using a return statement). John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter.

oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

More References Later

76

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2002/09/12/php_foundations.html See this if you're having trouble printing code examples

Advanced PHP References

by John Coggeshall 09/12/2002 Welcome back! In my last column I introduced you to basic PHP references and how they are used. This week, I'll take that basic introduction a step further and implement some of the more advanced uses for references in PHP. First, I'll be discussing the concept of returning a reference from a function, followed by using references within objects. Let's get started.

Returning by Reference Last week, I discussed how references could be used as parameters of functions in order to return multiple values. This week, I'll look at ways to use references as the actual return value of the function and how this can be useful to developers. To assist us in our discussion, consider the following classes:

printmsg() { "Class is A
";

printmsg() { "Class is B
";

A(); B();

As you can see, we have created two very simple classes, A and B, each of which contains a single member function called printmsg(). Then, an instance of each class is created and stored in the array $toolbox. With this overhead out of the way, let's discuss the passing by reference function. Although there are many uses for a return by reference function, the specific function that I will be creating today will accept a single parameter (for a simple case like this, a boolean value) and return a reference to one of the above created objects, as shown. Advanced PHP References

77

O'Reilly Network: An Introduction to PHP printmsg(); $anothertool =& selectObject(false); $anothertool−>printmsg(); ?>

So what exactly does this selectObject() function we've created do? Looking at the function declaration, we see that it takes a single boolean parameter $which, but what is the ampersand (&) character in front of the function name for? This symbol defines our function as one that returns a PHP reference instead of a complete variable. Looking at the code within the function, we can see that the function returns one of the objects stored in the $toolbox array defined previously. Hence, depending on the value of our parameter, we return a reference to one of the objects we've defined. Related Reading

PHP Cookbook By Adam Trachtenberg, David Sklar Table of Contents Index Sample Chapter Let's take a look at how the function is actually used. As you can see above, we have initialized the variable $tool to the value that selectObject() returns. Note that we are not using the standard syntax for a variable assignment, but rather the reference−binding syntax introduced in my last column. Since selectObject() is a reference−returning function, we must treat $tool as a reference variable and assign it using the appropriate "=&" syntax. Once properly assigned, $tool now points to the same object as the first index of the $toolbox array $toolbox[0] and represents the instance of class A. The same process is used to assign the $anothertool variable to the instance of class B (we just pass false as the parameter, instead of true). Although not particularly useful as shown, this method of using reference−returning functions is great when Advanced PHP References

78

O'Reilly Network: An Introduction to PHP working with search trees or other complex data structures, by allowing the developer to search through the data structure and return a reference to the exact piece of data in question!

References in Object Constructors Now that we've covered almost all there is to discuss regarding references, it's time to get to what probably is the most confusing reference phenomena −− referencing an object from within its constructor. Consider the following class: value = $val; } function printval() { echo "The value of this class is '{$this−>value}'
"; } function setval($val) { $this−>value = $val; } } ?>

Note that, in the constructor for this object, a global variable, $myref, is bound to a reference to $this (the pre−defined PHP reference to the object itself) and a member variable, $value, is set to the value of the passed parameter. When an instance of this class is created, a global variable, $myref, that points to this object will also be created. Hence, when this code is executed: printval(); $myref−>printval(); ?>

The output will be: The value of this class is 'FooBar!' The value of this class is 'FooBar!'

Now, what if we were to change the member variable within our instance of this class? From what we have learned thus far from references, any changes made through either the $myvar−>setval() or $myref−>setval() member functions should effectively change both. However, when the code below is executed: setval('Changed the value from $myvar'); $myvar−>printval(); $myref−>printval(); ?>

The resulting output is as follows: The value of this class is 'Change the value from $myvar'

References in Object Constructors

79

O'Reilly Network: An Introduction to PHP The value of this class is 'FooBar!'

Why didn't both change? The answer lies in when the object was first created. In PHP 4, the new statement does not return a reference by default. Rather, when the $myvar object was created, it returned a copy separate from the one referenced by the $myref variable. Thus, because they are separate instances of the same object, their variables are completely independent. To overcome this and achieve the desired result, we use the reference−binding operator when creating the objects, as shown: printval(); $myref−>printval(); $myvar−>setval('Now it works'); $myvar−>printval(); $myref−>printval(); ?>

And the output: The The The The

value value value value

of of of of

this this this this

class class class class

is is is is

'Foobar!' 'Foobar!' 'Now it works' 'Now it works'

That's All for Today That's about everything there is to know about PHP references. From what I've shown you, you should be well on your way to using references to make your PHP scripts faster and more efficient, without using more code! Next week, I'll be changing gears and introducing some of the fundamental concepts around working with the browser to make your PHP pages more interactive and dynamic. See you then! John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter.

oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

That's All for Today

80

O'Reilly Network: An Introduction to PHP

Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/php/2002/10/03/php_foundations.html See this if you're having trouble printing code examples

Working with Files in PHP

by John Coggeshall 10/03/2002 Welcome back. In my last column, I finished my discussion of using references in PHP to do some pretty powerful things. This week, I'll be changing gears completely and begin my discussion of working with the file system through the use of an extensive set of PHP functions. I'll cover the fundamentals of reading and writing text files first, then cover some of the more advanced features and offer a few great shortcut functions. Let's get started.

Basic File IO Opening and Closing Files The most versatile file IO (input and output) function available to the PHP developer is the fopen() (or file open) command. This function is the most common starting point for any file operations that occur within most PHP scripts. The syntax for the fopen() command is as follows: fopen(string filename, string mode [, int use_include_path])

The fopen() function when called returns an integer called a file reference (or pointer, depending on personal preference) or zero if the operation failed. This integer value in most cases must be saved into a variable because a great number of the file IO functions available to PHP require it as a parameter when called. As you can see, the fopen() function requires two parameters and allows an optional third. The first, the filename, obviously represents the name of the file in the file system that will be accessed. This file may or may not actually exist, depending on whether you are creating a new file or working with an existing one. The second required parameter, the mode, is used to determine how the file is intended to be accessed. The possible modes of access available in PHP are listed in the table below: String Access Mode r

Access the file for reading only, start access from beginning of the file.

r+

Access the file for both reading and writing, start access f from beginning of the file.

Working with Files in PHP

81

O'Reilly Network: An Introduction to PHP w

Access the file for writing only, If the file exists, erase all contents. If file does not exist, an attempt will be made to create the file. In either case access the file from the beginning.

w+

Access the file for both reading and writing, If the file exists erase all contents. If the file does not exist, an attempt will be made to create the file. In either case, access the file from the beginning.

a

Open the file for writing only. If the file does not exist, an attempt will be made to create it. If the file does exist, access will start from the end of the file (no erasing).

a+

Open the file for reading and writing. If the file does not exist, an attempt will be made to create it. If the file does exist, access will start from the end of the file (no erasing).

As you can see, these modes can be boiled down into three basic groups: reading, writing, and appending. Only one of these strings may be used as the mode parameter for the fopen() command. Related Reading

PHP Cookbook By Adam Trachtenberg, David Sklar Table of Contents Index Sample Chapter The final optional parameter use_include_path is an integer representing a boolean value. If the value of this parameter is true (an integer value of 1,) then when an attempt is made to open a file that does not exist in the specified directory, an attempt will be made to file the file in the directories specified by PHP's include path before further action is taken. Important note: In order for a file to be accessed or created, the directory and/or file in question must have the appropriate permissions. Also note that access must be granted to the user under which the PHP script will be executed (usually the same username as the web server). Once a file reference has been created, and any reading/writing done to the file opened is complete, it is necessary that the file be closed before it can be opened again. Although all file references are automatically closed upon the termination of the PHP script which opened them, it is good programming practice to close the files manually. To do this, PHP provides the fclose() function. This function takes a single parameter (the file reference) and returns a boolean value indicating the success or failure. Working with Files in PHP

82

O'Reilly Network: An Introduction to PHP For example, the below code will open and close a file in the /tmp/ directory called test.txt using the a+ (Append read/write) mode:

Reading and Writing Strings Now that we have discussed opening a file, how do we read any data from it? Although there are many different methods, one of the most basic methods is the fgets() function. The syntax for the fgets() function is as follows: fgets(int file reference [, int length])

As you can see, the only required parameter to the fgets() function is the file reference returned by the fopen() function. The optional parameter represents the number of bytes to read from the file (minus one). If this parameter is not provided, the fgets() will read one kilobyte (1024 bytes) from the file until a new line character is read or until the function reaches the end of the file. The return value from the fgets() function is the string read from the file. Please note that in the event that the fgets() function stops reading because a new line character is encountered, the new line character will be returned as part of the string. This is not true, however, if the end of file is reached. In that case, the end of file character is omitted from the resulting string. Of course, for this function to work the file reference used must have been created by opening a file in the proper mode (any mode allowing reading). The complement of the fgets() function, fputs() is the basic function available in PHP for writing a string to a file. Unlike fgets(), fputs() requires a minimum of two parameters (the file reference and the string to write) with a third optional parameter representing the amount of the passed string to actually write to the file. Now that we are familiar with the ways to open, close, read, and write to a file in PHP, let's make a simple counter script. The purpose of this script is simply to count the number of times the script has been executed. When placed on a Web page, this script can be used to count the number of times the page has been viewed. To create this script we'll need to store an string representing the number of times the page has been accessed into a file, then every time the script is executed, we'll read that value, add one, and write it back to the file. Let's get started. First, we'll need to open the file. For our purposes, I'll use the file counter.txt in the /tmp/ directory for reading:
Basic File IO

// Initialize the visitors to zero

83

O'Reilly Network: An Introduction to PHP $fr = fopen('/tmp/counter.txt', 'r');

Because the first time the script is executed, the file shouldn't exist we have to first test the file reference to see if the fopen() command was successful. If not we need to create the file, set the total visitors to one, and write that value into the file: if(!$fr) { $visitors = 1; // Our first visitor $fr = fopen('/tmp/counter.txt','w'); if(!$fr) { echo "Could not create the counter file!"; exit; } fputs($fr, $visitors); fclose($fr);

If we were successful at opening the counter.txt file, then our next step is to read the string containing the total visitors from the file, add one to it, and display it to the user: } else { $visitors = fgets($fr); $visitors++; echo "You are visitor number: $visitors";

Now, we need to close the current file reference (as it's in the wrong mode) and re−open the file in writing mode. Once that's done, we can write the new visitor number back to the file, close it, and we're all done: fclose($fr); $fr = fopen('/tmp/counter.txt','w'); if(!$fr) { echo "Could not re−create the counter file!"; exit; } fputs($fr, $visitors); fclose($fr); } ?>

That's All for Today That concludes our introduction to accessing the file system with PHP. Now that you are familiar with some of the fundamental functions used when accessing files, in the coming weeks I'll be continuing our discussion including some shortcuts, dealing with permissions and working with the directory structure. See you then. Editor's Note, 8 October 2002: due to an unfortunate typo, the previous versions of this article left out the initial argument to the fputs() calls. This has now been fixed. John Coggeshall is a private Web consultant and graphics designer with over 10 years of development experience, and 5 years of PHP experience. Read more PHP Foundations columns. Return to the PHP DevCenter. That's All for Today

84

O'Reilly Network: An Introduction to PHP

oreillynet.com Copyright © 2000 O'Reilly & Associates, Inc.

That's All for Today

85

Related Documents