Saturday, November 1, 2008

Variables

As a byproduct of examining the examples up to this point, I’ve introduced you to how variables are assigned and manipulated. However, it would be wise to explicitly
lay the groundwork as to how variables are declared and manipulated. The coming sections will examine these rules in detail.

Variable Declaration


A variable is a named memory location that contains data that may be manipulated throughout the execution of the program. A variable always begins with a dollar sign, $. The following are all valid variables:
$color
$operating_system
$_some_variable
$model
Variable names follow the same naming rules as those set for identifiers. That is, a variable name can begin with either an alphabetical letter or underscore and
can consist of alphabetical letters, underscores, integers, or other ASCII characters ranging from 127 through 255. Interestingly, variables do not have to be explicitly declared in PHP, much as is the case with the Perl language. Rather, variables can be declared and assigned values simultaneously. Furthermore, a variable’s data type is implicitly determined by examining the kind of data that the variable holds. Consider the following example:
$sentence = "This is a sentence."; // $sentence evaluates to string.
$price = 42.99; // $price evaluates to a floating-point
$weight = 185; // $weight evaluates to an integer.
You can declare variables anywhere in a PHP script. However, the location of the declaration greatly influences the realm in which a variable can be accessed. This access domain is known as its scope.

Variable Scope


Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:
Local variables
• Function parameters
• Global variables
• Static variables

Identifiers

An identifier is a general term applied to variables, functions, and various other user-defined objects. There are several properties that PHP identifiers must abide by:
An identifier can consist of one or more characters and must begin with an
alphabetical letter or an underscore
. Furthermore, identifiers can only consist
of letters, numbers, underscore characters, and other ASCII characters
from 127 through 255. Consider a few examples:
VALID INVALID
my_function This&that
Size !counter
_someword 4ward
Identifiers are case sensitive. Therefore, a variable named $recipe is different
from variables named $Recipe, $rEciPe, or $recipE.
Identifiers can be any length. This is advantageous, as it enables a programmer
to accurately describe the identifier’s purpose via the identifier name.
Finally, an identifier name can’t be identical to any of PHP’s predefined keywords.

Variables and Data Types (3)

Objects


The fifth PHP data type is the object. You can think of an object as a variable that is instantiated from a kind of template otherwise known as a class. The concept of objects and classes is integral to the notion of object-oriented programming (OOP). Contrary to the other data types contained in the PHP language, an object
must be explicitly declared. It is important to realize that an object is nothing more than a particular instance of a class, which acts as a template for creating objects having specific characteristics and functionality. Therefore, a class must be defined before an object can be declared. A general example of class declaration and subsequent object instantiation follows:
class appliance {
var power;
function set_power($on_off) {
$this->power = $on_off;
}
}
. . .
$blender = new appliance;
A class definition creates several characteristics and functions pertinent to a data structure, in this case a data structure named appliance. So far, the appliance isn’t very functional. There is only one characteristic: power. This characteristic can be modified by using the method set_power. Remember, however, that a class definition is a template and cannot itself be manipulated. Instead, objects are created based on this template. This is accomplished via the new keyword. Therefore, in the preceding listing an object of class appliance named blender is created. The blender power can then be set by making use of the method set_power:
$blender->set_power("on");, “Object-Oriented PHP,” introduces PHP’s OOP implementation in further
detail.

Boolean, or True/False, Values


The boolean data type is essentially capable of representing only two data types: true and false. Boolean values can be determined in two ways: as a comparison evaluation or from a variable value. Both are rather straightforward. Comparisons can take place in many forms. Evaluation typically takes place by use of a double equal sign and an if conditional. Here is an example:
if ($sum == 40) :
. . .
This could evaluate to only either true or false. Either $sum equals 40, or it does not. If $sum does equal 40, then the expression evaluates to true. Otherwise, the result is false. Boolean values can also be determined via explicitly setting a variable to a true or false value. Here is an example:
$flag = TRUE;
if ($flag == TRUE) :
print "The flag is true!";
else :
print "The flag is false!";
endif;
If the variable $flag has been set to true, then print the appropriate statement; Otherwise, print an alternative statement. An alternative way to represent true and false is by using the values 1 and 0, respectively. Therefore, the previous example can be restated as follows:
$flag = 1;
if ($flag == TRUE) :
print "The flag is true!";
else :
print "The flag is false !";
endif;
Yet another alternative way to represent the above example follows:
$flag = TRUE;
// this implicitly asks "if ($flag == TRUE)"
if ($flag) :
print "The flag is true!";
else :
print "The flag is false!";
endif;

Variables and Data Types (2)

Arrays


An array is a list of elements each having the same type. There are two types of arrays: those that are accessed in accordance with the index position in which the
element resides, and those that are associative in nature, accessed by a key value that bears some sort of association with its corresponding value. In practice, however,
both are manipulated in much the same way. Arrays can also be single dimensional or multidimensional in size.

Single-Dimension Indexed Arrays


Single-dimension indexed arrays are handled using an integer subscript to denote the position of the requested value. The general syntax of a single-dimension array is:
$name[index1];
A single-dimension array can be created as follows:
$meat[0] = "chicken";
$meat[1] = "steak";
$meat[2] = "turkey";
If you execute this command:
print $meat[1];
The following will be output to the browser:
steak
Alternatively, arrays may be created using PHP’s array() function. You can use this function to create the same $meat array as the one in the preceding example:
$meat = array("chicken", "steak", "turkey");
Executing the same print command yields the same results as in the previous example, again producing “steak”. You can also assign values to the end of the array simply by assigning values to an array variable using empty brackets. Therefore, another way to assign values
to the $meat array is as follows:
$meat[] = "chicken";
$meat[] = "steak";
$meat[] = "turkey";

Single-Dimension Associative Arrays


Associative arrays are particularly convenient when it makes more sense to map an array using words rather than integers. For example, assume that you wanted to keep track of all of the best food and wine pairings. It would be most convenient if you could simply assign the arrays using key-value pairings, for example, wine to dish. Use of an associative array to store this information would be the wise choice:
$pairings["zinfandel"] = "Broiled Veal Chops";
$pairings["merlot"] = "Baked Ham";
$pairings["sauvignon"] = "Prime Rib";
$pairings["sauternes"] = "Roasted Salmon";
Use of this associative array would greatly reduce the time and code required to display a particular value. Assume that you wanted to inform a reader of the best accompanying dish with merlot. A simple call to the pairings array would produce the necessary output:
print $pairings["merlot"]; // outputs the value "Baked Ham"
An alternative method in which to create an array is via PHP’s array() function:
$pairings = array(
zinfandel => "Broiled Veal Chops",
merlot => "Baked Ham",
sauvignon => "Prime Rib",
sauternes => "Roasted Salmon";
This assignment method bears no difference in functionality from the previous $pairings array, other than the format in which it was created.

Multidimensional Indexed Arrays


Multidimensional indexed arrays function much like their single-dimension counterparts, except that more than one index array is used to specify an element. There is no limit as to the dimension size, although it is unlikely that anything beyond three dimensions would be used in most applications. The general syntax of a multidimensional array is:
$name[index1] [index2]..[indexN];
An element of a two-dimensional indexed array could be referenced as follows:
$position = $chess_board[5][4];

Multidimensional Associative Arrays


Multidimensional associative arrays are also possible (and quite useful) in PHP. Assume you wanted to keep track of wine-food pairings, not only by wine type, but also by producer. You could do something similar to the following:
$pairings["Martinelli"] ["zinfandel"] = "Broiled Veal Chops";
$pairings["Beringer"] ["merlot"] = "Baked Ham";
$pairings["Jarvis"] ["sauvignon"] = "Prime Rib";
$pairings["Climens"] ["sauternes"] = "Roasted Salmon";

Mixing Indexed and Associative Array Indexes


It is also possible to mix indexed and associative arrays indexes. Expanding on the single-dimension associative array example, suppose you wanted to keep track of the first and second string players of the Ohio State Buckeyes football team. You could do something similar to the following:
$Buckeyes["quarterback"] [1] = "Bellisari";
$Buckeyes["quarterback"] [2] = "Moherman";
$Buckeyes["quarterback"] [3] = "Wiley";
PHP provides a vast assortment of functions for creating and manipulating arrays, so much so that the subject merits an entire chapter.

Variables and Data Types

Data types form the backbone of any programming language, providing the programmer with a means by which to represent various types of information. PHP provides support for six general data types:
• Integers
• Floating-point numbers
• Strings
• Arrays
• Objects
• Booleans

One of the pillars of any programming language is its support for numbers. PHP supports both integers and real (double) numbers. Each of these number formats is described in further detail later.

Integer Values


An integer is nothing more than a whole number. Integers are represented as a series of one or more digits. Some examples of integers are:
5
591
52
31

Octals and Hexadecimals


Integers in octal (base 8) and hexadecimal (base 16) formats are supported. Octal values begin with the digit 0, followed by a sequence of digits, each ranging from 0 to 7. Some examples of octal integers are:
0422
0534
Hexadecimal integers can consist of the digits 0 through 9 or the letters a (A) through f (F). All hexadecimal integers are preceded by 0x or 0X. Some examples of hexadecimal integers are:
0x3FF
0X22abc

Floating-Point Numbers


A floating-point number is essentially a real numbers, that is, a number denoted either wholly or in part by a fraction. Floating-point numbers are useful for representing values that call for a more accurate representation, such as temperature or monetary figures. PHP supports two floating-point formats: standard notation and scientific notation.

Standard Notation


Standard notation is a convenient representation typically used for real numbers, for example, monetary values. Some examples are:
12.45
98.6

Scientific Notation


Scientific notation is a more convenient representation for very large and very small numbers, such as interplanetary distances or atomic measurements. Some examples include:
3e8
5.9736e24
Chapter 2
32

String Values


A string is a group of characters that are represented as a single entity but can also be examined on a character-by-character basis. Some examples of strings are: thesaurus
49ers
abc
&%/$£
Note that PHP doesn’t include support for the char data type. Rather, the string data type can be considered the all-encompassing type that represents both single and multiple character sets.

String Assignments


Strings can be delimited in two ways, using either double quotation marks (“”) or single quotation marks (‘’). There are two fundamental differences between the two methods. First, variables in a double-quoted string will be replaced with their respective values, whereas the single-quoted strings will be interpreted exactly as is, even if variables are enclosed in the string. The following two string declarations produce the same result:
$food = "meatloaf";
$food = 'meatloaf';
However, the following two declarations result in two drastically different outcomes:
$sentence = "My favorite food is $food";
$sentence2 = 'My favorite food is $food';
The following string is what exactly will be assigned to $sentence. Notice how the variable $food is automatically interpreted:
My favorite food is meatloaf.
Whereas $sentence2 will be assigned the string as follows:
My favorite food is $food.
In contrast with $sentence, the uninterpreted variable $food will appear in the string assigned to $sentence2. These differing outcomes are due to the usage of double and single quotation marks in assigning the corresponding strings to $sentence and $sentence2. Before discussing the second fundamental difference between doublequoted and single-quoted strings, an introduction of PHP’s supported string delimiters is in order. As with most other mainstream languages, a set of delimiters is used to represent special characters, such as the tab or newline characters.

Sunday, October 26, 2008

Characteristics of PHP

As you may have realized, the PHP language revolves around the central theme of practicality. PHP is about providing the programmer with the necessary tools to get the job done in a quick and efficient fashion. Five important characteristics make PHP’s practical nature possible:
Familiarity
Simplicity
Efficiency
Security
Flexibility
One final characteristic makes PHP particularly interesting: it’s free!

Familiarity

Programmers from many backgrounds will find themselves already accustomed to the PHP language. Many of the language’s constructs are borrowed from C and Perl, and in many cases PHP code is almost indistinguishable from that found in the typical C or Pascal program. This minimizes the learning curve considerably.

Simplicity

A PHP script can consist of 10,000 lines or one line: whatever you need to get the job done. There is no need to include libraries, special compilation directives, or anything of the sort. The PHP engine simply begins executing the code after the first escape sequence (<?) and continues until it passes the closing escape sequence (?>). If the code is syntactically correct, it will be executed exactly as it is displayed.

Efficiency

Efficiency is an extremely important consideration for working in a multiuser environment such as the WWW. PHP 4.0 introduced resource allocation mechanisms and more pronounced support for object-oriented programming, in addition to session management features. Reference counting has also been introduced in the latest version, eliminating unnecessary memory allocation.

Security

PHP provides developers and administrators with a flexible and efficient set of security safeguards. These safeguards can be divided into two frames of reference: system level and application level.
System-Level Security Safeguards
PHP furnishes a number of security mechanisms that administrators can manipulate, providing for the maximum amount of freedom and security when PHP is properly configured. PHP can be run in what is known as safe mode, which can limit users’ attempts to exploit the PHP implementation in many important ways. Limits can also be placed on maximum execution time and memory usage, which if not controlled can have adverse affects on server performance. Much as with a cgi-bin folder, administrators can also place restrictions on the locations in which users can view and execute PHP scripts and use PHP scripts to view guarded server information, such as the passwd file.
Application-Level Security Safeguards
Several trusted data encryption options are supported in PHP’s predefined function set. PHP is also compatible with many third-party applications, allowing for easy-integration with secure ecommerce technologies. Another advantage is that the PHP source code is not viewable through the browser because the script is completely parsed before it is sent back to the requesting user. This benefit of PHP’s server-side architecture prevents the loss of creative scripts to users at least knowledgeable enough to execute a ‘View Source’.
Security is such an important issue that this book contains an entire chapter
on the subject. Please read Chapter 16, “Security,” for a thorough accounting of
PHP’s security features.

Flexibility

Because PHP is an embedded language, it is extremely flexible towards meeting the needs of the developer. Although PHP is generally touted as being used in conjunction solely with HTML, it can also be integrated alongside languages like JavaScript, WML, XML, and many others. Additionally, as with most other mainstream languages, wisely planned PHP applications can be easily expanded as needed. Browser dependency is not an issue because PHP scripts are compiled entirely on the server side before being sent to the user. In fact, PHP scripts can be sent to just about any kind of device containing a browser, including cell phones, personal digital assistant (PDA) devices, pagers, laptops, not to mention the traditional PC. People who want to develop shell-based applications can also execute PHP from the command line. Since PHP contains no server-specific code, users are not limited to a specific
and perhaps unfamiliar Web server. Apache, Microsoft IIs, Netscape Enterprise Server, Stronghold, and Zeus are all fair game for PHP’s server integration. Because of the various platforms that these servers operate on, PHP is largely platform independent, available for such platforms as UNIX, Solaris, FreeBSD, and Windows 95/98/NT. Finally, PHP offers access to external components, such as Enterprise Java Beans and Win32 COM objects. These newly added features put PHP in the big league, truly enabling developers to scale PHP projects upward and outward as need be.

Free

The open source development strategy has gained considerable notoriety in the software industry. The prospect of releasing source code to the masses has resulted in undeniably positive outcomes for many projects, perhaps most notably Linux, although the success of the Apache project has certainly been a major contributor in proving the validity of the open source ideal. The same holds true for the developmental history of PHP, as users worldwide have been a huge factor in the advancement of the PHP project. PHP’s embracing of this open source strategy result in great performance gains for users, and the code is available free of charge. Additionally, an extremely receptive user community numbering in the thousands acts as “customer support,” providing answers to even the most arcane questions in popular online discussion groups. The next section, “User Affirmations,” provides testimonies from three noted industry professionals. Each provides keen insight into why they find PHP such an appealing technology.

An Introduction to PHP

The past five years have been fantastic in terms of the explosive growth of the Internet and the new ways in which people are able to communicate with one another. Spearheading this phenomenon has been the World Wide Web (WWW), with thousands of new sites being launched daily and consumers being consistently offered numerous outstanding services via this new communications medium. With this exploding market has come a great need for new technologies and developers to learn these technologies. Chances are that if you are reading this paragraph, you are one of these Web developers or are soon to become one. Regardless of your profession, you’ve picked this book up because you’ve heard of the great new technology called PHP. This chapter introduces the PHP language, discusses its history and capabilities, and provides the basic information you need to begin developing PHPenabled sites. Several examples are provided throughout, hopefully serving to excite you about what PHP can offer you and your organization. You will learn how to install and configure the PHP software on both Linux/UNIX and Windows machines, and you will learn how to embed PHP in HTML. At the conclusion of the chapter, you will be ready to begin delving into the many important aspects of the PHP language. So light the fire, turn on your favorite jazz album, and curl up on the lazyboy; you are about to learn what will be one of the most exciting additions to your resume: PHP programming.

An Abbreviated History



PHP set its roots in 1995, when an independent software development contractor named Rasmus Lerdorf developed a Perl/CGI script that enabled him to know how many visitors were reading his online resume. His script performed two duties: logging visitor information and displaying the count of visitors to the Web page. Because the WWW as we know it today was still so young at that time, tools such as these were nonexistent, and they prompted emails inquiring about Lerdorf’s scripts. Lerdorf thus began giving away his toolset, dubbed Personal Home Page (PHP), or Hypertext Preprocessor. The clamor for the PHP toolset prompted Lerdorf to begin developing additions to PHP, one of which converted data entered in an HTML form into symbolic variables that allowed for their export to other systems. To accomplish this, he opted to continue development in C code rather than Perl. This addition to the 3 existing PHP toolset resulted in PHP 2.0, or PHP-FI (Personal Home Page—Form Interpreter). This 2.0 release was accompanied by a number of enhancements
and improvements from programmers worldwide. The new PHP release was extremely popular, and a core team of developers soon formed. They kept the original concept of incorporating code directly alongside HTML and rewrote the parsing engine, giving birth to PHP 3.0. By the 1997 release of version 3.0, over 50,000 users were using PHP to enhance their Web pages. Development continued at a hectic pace over the next two years, with hundreds of functions being added and the user count growing in leaps and bounds. At the onset of 1999, Netcraft reported a conservative estimate of a user base surpassing 1,000,000, making PHP one of the most popular scripting languages in the world. Early 1999 saw the announcement of the upcoming PHP 4.0. Although one of PHP’s strongest features was its proficiency at executing scripts, the developers had not intended that large-scale applications were going to be built using PHP. Thus they set out to build an even-more robust parsing engine, better known as Zend. Development continued rapidly, culminating in the May 22, 2000, release of PHP 4.0. In addition to the Zend processor, Zend technologies, based in Israel, offers the Zend optimizer, which increases even further the performance benefits of the Zend parsing engine. Available for download free of charge, the benchmarks have shown that the optimizer can result in a 40 to 100 percent overall performance gain. Check out the Zend site for more information. At the time of this writing, according to Netcraft, PHP is installed on over 3.6 million domains, making it one of the most popular scripting languages in the world. The future of PHP indeed looks bright, as major Web sites and personal users alike continue to embrace the product. PHP is best summarized as an embedded server-side Web-scripting language that provides developers with the capability to quickly and efficiently build dynamic Web applications. PHP bears a close resemblance, both syntactically and grammatically, to the C programming language, although developers haven’t been shy to integrate features from a multitude of languages, including Perl, Java, and C++. Several of these valuable borrowed features include regular expression parsing, powerful array-handling capabilities, an object-oriented methodology, and vast database support. For writing applications that extend beyond the traditional, static methodology of Web page development (that is, HTML), PHP can also serve as a valuable tool for creating and managing dynamic content, embedded directly beside the likes of JavaScript, Stylesheets, WML (Wireless Markup Language) and many other useful languages. Providing hundreds of predefined functions, PHP is capable of handling just about anything a developer can dream of. Extensive support is offered for graphic creation and manipulation, mathematical calculations, ecommerce, and burgeoning technologies such as Extensible Markup Language (XML), open database connectivity (ODBC), and Macromedia Shockwave. This vast range of capabilities eliminates the need for the tedious and costly integration of several third-party modules, making PHP the tool of choice for developers worldwide. One of the main strengths of PHP is the fact that because it can be embedded directly alongside HTML code, there is no need to write a program that has many commands just to output the HTML. HTML and PHP can be used interchangeably as needed, working alongside one another in unison. With PHP, we can simply do the following:
<html> <title><? print "Hello world!"; ?></title>
</html> And Hello world! will be displayed in the Web page title bar. Interestingly, the single line print statement is enclosed in what are commonly known as PHP’s escape characters () is a complete program. No need for lengthy prefacing code or inclusion of libraries; the only required code is what is needed to get the job done! Of course, in order to execute a PHP script, you must first install and configure the PHP software on your server. This process is explained in “Downloading and Installing PHP/Apache,” later in this chapter. Immediately preceding that section are a few excerpts from prominent users testifying to the power of PHP, followed by a detailed synopsis of the language and its history. However, before diving into the installation process, take a moment to read more about the characteristics of PHP that make it such a powerful language. This is the subject of the next section, aptly titled “Characteristics of PHP.”