01 7090 Intro 7/16/04 8:43 AM Page 4
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
1
The Basics of PHP
PHP IS THE MOST POPULAR WEB-DEVELOPMENT language in the world. According to
estimates compiled in April 2004, there are over fifteen million unique domains—and
almost two million unique IPs—on the World Wide Web that reside on servers where
PHP is supported and used.
The term “PHP” is actually a “recursive acronym” that stands for PHP: Hypertext
Preprocessor. It might look a bit odd, but it is quite clever, if you think of it. PHP is a
“scripting language”—a language intended for interpretation and execution rather than
compilation such as, for example, C.
The fact that PHP is interpreted and not compiled, however, does not mean that it is
incapable of meeting the demands of today’s highly intensive web environments—in fact,
a properly written PHP script can deliver incredibly high performance and power.
Terms You’ll Need to Understand
n
Language and Platform
n
Language construct
n
Data type
n
Opening and closing tags
n
Expression
n
Variable
n
Operation and operator precedence
n
Conditional structures
n
Iteration and Loops
n
Functions
n
Variable variables and variable functions
02 7090 ch01 7/16/04 8:44 AM Page 5
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
6
Chapter 1 The Basics of PHP
Techniques You’ll Need to Master
n
Creating a script
n
Entering PHP mode
n
Handling data types
n
Type casting and type juggling
n
Creating statements
n
Creating operations and expressions
n
Writing functions
n
Handling conditional statements
n
Handling loops
Language and Platform
The two biggest strengths of PHP are its simplicity and the incredible set of functionality
that it provides.As a language, it incorporates C’s elegant syntax without the hassle of
memory and pointer management, as well as Perl’s powerful constructs—without the
complexity often associated with Perl scripts.
As a platform, PHP provides a powerful set of functions that cover a multitude of dif-
ferent needs and capabilities. Programmers who work on commercial platforms such as
Microsoft ASP often marvel at the arsenal of functionality that a PHP developer has at
his fingertips without the need to purchase or install anything other than the basic inter-
preter package.What’s more, PHP is also extensible through a set of well-defined C APIs
that make it easy for anyone to add more functionality to it as needed.
You have probably noticed that we have made a distinction between “language” and
“platform.” By the former, we mean PHP proper—the body of syntactical rules and
constructs that make it possible to create a set of commands that can be executed in a
particular sequence.The latter, on the other hand, is a term that we use to identify those
facilities that make it possible for the language to perform actions such as communicat-
ing with the outside, sending an email, or connecting to a database.
The certification exam verifies your knowledge on both the language and the plat-
form—after all, a good programmer needs to know how to write code and how to use
all the tools at his disposal. Therefore, it is important that you acquaint yourself with
both aspects of PHP development in order to successfully pass the exam.
Getting Started
The basic element of a PHP application is the script. A PHP script contains a number of
commands that the PHP interpreter reads, parses, and executes.
02 7090 ch01 7/16/04 8:44 AM Page 6
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
7
Getting Started
Because PHP is designed to manipulate text files—such as HTML documents—and
output them, the process of mixing hard-coded textual content and PHP code is facili-
tated by the fact that unless you tell it otherwise, the PHP interpreter considers the con-
tents of the script file as plain text and outputs them as they are.
It’s only when you explicitly indicate that you are embedding PHP code inside a file
that the interpreter goes to work and starts parsing and executing commands.This is
done by using a special set of opening and closing tags. In part because of historical reasons
and in order to promote maximum flexibility, PHP supports three different sets of tags:
n
PHP opening (<?php) and closing (?>) tags
n
HTML-style tags (<script language=”php”> and </script>)
n
“Short” tags: <? and ?>
n
“ASP-style” tags: <% and %>
The full PHP tags are always available to a script, whereas short tags and ASP-style tags
might or might not be available to your script, depending on how the particular installa-
tion of the PHP interpreter used to execute it is configured.This is made necessary by
the fact that short tags can interfere with XML documents, whereas ASP-style tags can
interfere with other languages that can be used in conjunction with PHP in a chain of
preprocessors that manipulate a file multiple times before it is outputted.
Let’s take a look at the following sample PHP script:
<html>
<head>
<title>
This is a sample document
</title>
<body>
<?php
echo ‘This is some sample text’;
?>
</body>
</html>
As you can see, this document looks exactly like a normal HTML page until the inter-
preter hits the <?php tag, which indicates that text following the tag should be interpret-
ed as PHP commands and executed.
Right after the opening tag, we see a line of PHP code, which we’ll examine in detail
later on, followed by the ?> closing tag.After the interpreter sees the closing tag, it stops
trying to parse PHP commands and simply outputs the text as it appears without any
change. Note that, as long as your copy of PHP has been configured to support more
than one type of opening and closing tags, you can mix and match opening and closing
tags from different families—for example, <?php echo ‘a’ %> would be a valid script.
From a practical perspective, however, doing so would be pointless and confusing—defi-
nitely not a good programming practice.
02 7090 ch01 7/16/04 8:44 AM Page 7
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
8
Chapter 1 The Basics of PHP
Naturally, you can switch between plain-text and PHP execution mode at any point
during your script and as long as you remember to balance your tags—that is, to close
any tags you open, you can switch an arbitrary number of times.
The Special <?= ?> Tags
A special set of tags, <?= and ?>, can be used to output the value of an expression direct-
ly to the browser (or, if you’re not running PHP in a web environment to the standard
output).They work by forcing PHP to evaluate the expression they contain and they
output its value. For example,
<?= “This is an expression” ?>
Scripts and Files
It’s important to note that there isn’t necessarily a one-to-one correspondence between
scripts and files—in fact, a script could be made up of an arbitrary number of files, each
containing one or more portions of the code that must be executed. Clearly, this means
that you can write portions of code so that they can be used by more than one script,
such as library, which makes a PHP application even more flexible.
The inclusion of external files is performed using one of four different language con-
structs:
n
include, which reads an external file and causes it to be interpreted. If the inter-
preter cannot find the file, it causes a warning to be produced and does not stop
the execution of the script.
n
require, which differs from include in the way it handles failure. If the file to be
included cannot be found, require causes an error and stops the script’s execu-
tion.
n
require_once and include_once, which work in a similar way to require and
include, with one notable difference: No matter how many times you include a
particular file, require_once and include_once will only read it and cause it to
be interpreted once.
The convenience of require_once and include_once is quite obvious because you
don’t have to worry about a particular file being included more than once in any given
script—which would normally cause problems because everything that is part of the file
would be interpreted more than once. However, generally speaking, situations in which a
single file is included more than once are often an indicator that something is not right
in the layout of your application. Using require_once or include_once will deprive
you of an important debugging aid because you won’t see any errors and, possibly, miss a
problem of larger magnitude that is not immediately obvious. Still, in some cases there is
no way around including a file more than once; therefore, these two constructs come in
very handy.
02 7090 ch01 7/16/04 8:44 AM Page 8
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
9
Manipulating Data
Let’s try an example.We’ll start with a file that we will call includefile.php:
<?php
echo ‘You have included a file’;
?>
Next, we’ll move on to mainfile.php:
<?php
include ‘includefile.php’;
echo ‘I should have included a file.’;
?>
If you make sure to put both files in the same directory and execute mainfile.php,you
will notice that includefile.php is included and executed, causing the text You have
included a file to be printed out.
Note that if the two files are not in the same folder, PHP will look for
includefile.php in the include path.The include path is determined in part by the
environment in which your script is running and by the php.ini settings that belong to
your particular installation.
Manipulating Data
The manipulation of data is at the core of every language—and PHP is no exception. In
fact, handling information of many different types is very often one of the primary tasks
that a script must perform; it usually culminates with the output of some or all the data
to a device—be it a file, the screen, or the Internet.
When dealing with data, it is often very important to know what type of data is being
handled. If your application needs to know the number of times that a patient has visited
the hospital, you want to make sure that the information provided by the user is, indeed,
a number, and an integer number at that because it would be difficult for anybody to
visit the hospital 3.5 times. Similarly, if you’re asking for a person’s name, you will, at the
very least, ensure that you are not being provided with a number, and so on.
Like most modern languages, PHP supports a variety of data types and is capable of
operating them in several different ways.
Numeric Values
PHP supports two numeric data types: integer and real (or floating-point). Both types
correspond to the classic mathematical definition of the types—with the exception that
real numbers are stored using a mechanism that makes it impossible to represent certain
numbers, and with a somewhat limited precision so that, for example, 2 divided by 3 is
represented as 0.66666666666667.
02 7090 ch01 7/16/04 8:44 AM Page 9
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
10
Chapter 1 The Basics of PHP
Numeric values in base 10 are represented only by digits and (optionally) a dot to
separate units from fractional values.The interpreter does not need commas to group the
integer portion of the value in thousands, nor does it understand it, producing an error if
you use a format such as 123,456. Similarly, the European representation (comma to sep-
arate the fractional part of the value from the integer one) is not supported.
As part of your scripts, you can also enter a value in hexadecimal (base 16) represen-
tation—provided that it is prefixed by 0x, and that it is an integer. Both uppercase and
lowercase hexadecimal digits are recognized by the interpreter, although traditionally
only lowercase ones are actually used.
Finally, you can represent an integer value in octal (base 8) notation by prefixing it
with a single zero and using only digits between 0 and 7.Thus, the value 0123 is not the
same as 123.The interpreter will parse 0123 as an octal value, which actually corresponds
to 83 in decimal representation (or 0x53 in hexadecimal).
String Values
Although we often think of strings as pieces of text, a string is best defined as a collec-
tion of bytes placed in a specific order.Thus, a string could contain text—say, for example,
a user’s first and last name—but it could also contain arbitrary binary data, such as the
contents of a JPEG image of a MIDI file.
String values can be declared using one of three methods.The simplest one consists of
enclosing your string in single quotes:
‘This is a simple string’
The information between the quotes will be parsed by the interpreter and stored with-
out any modification in the string. Naturally, you can include single quotation marks in
your string by “escaping” them with a backslash:
‘He said: \’This is a simple string\’’
And this also means that, if you want to include a backslash, you will have to escape it as
well:
‘The file is in the c:\\test directory’
Another mechanism used to declare a string uses double quotation marks.This approach
provides a bit more flexibility than the previous one, as you can now include a number
of special characters through specific escape sequences:
n
\n—A line feed
n
\r—A carriage return
n
\t—A horizontal tab
n
\\—A backslash
n
\”—A double quote
n
\nnn—A character corresponding to the octal value of nnn (with each digit being
between 0 and 7)
n
\xnn—A character corresponding to the hexadecimal value of nn
02 7090 ch01 7/16/04 8:44 AM Page 10
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
11
Manipulating Data
Double-quote strings can also contain carriage returns. For example, the following
strings are equivalent:
“This\nis a string”
“This
is a string”
The final method that you can use to declare a string is through the heredoc syntax:
<<<ENDOFTEXT
My text goes here.
More text can go on another line.
You can even use escape sequences: \t
ENDOFTEXT;
As you can see, the <<< heredoc tag is followed by an arbitrary string of text (which
we’ll call the marker) on a single line.The interpreter will parse the contents of the file as
a string until the marker is found, on its own, at the beginning of a line, followed by a
semicolon. Heredoc strings can come in handy when you want to embed large amounts
of text in your scripts—although you can sometimes achieve a similar goal by simply
switching in and out of PHP mode.
Boolean Values
A Boolean value can only be True or False.This type of value is generally used in
Boolean expressions to change the flow of a script’s execution based on certain condi-
tions.
Note that, although PHP defines True and False as two valid values when printed,
Boolean values are always an empty string (if false) or the number 1 (if true).
Arrays
Arrays are an aggregate value—that is, they represent a collection of other values. In PHP,
arrays can contain an arbitrary number of elements of heterogeneous type (including
other arrays). Each element is assigned a key—another scalar value used to identify the
element within the array.You’ll find this particular data type discussed in greater detail in
Chapter 4,“Arrays.”
Objects
Objects are self-contained collections of code and data.They are at the core of object-
oriented programming and can provide a very valuable tool for creating solid, enter-
prise-level applications.They are described in Chapter 2,“Object-Oriented PHP.”
The NULL Data Type
It is sometimes important to indicate that a datum has “no value”. Computer languages
need a special value for this purpose because even zero or an empty string imply that a
value and a type have been assigned to a datum.
The NULL value, thus, is used to express the absence of any type of value.
02 7090 ch01 7/16/04 8:44 AM Page 11
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
12
Chapter 1 The Basics of PHP
Resources
A resource is a special type of value that indicates a reference to a resource that is exter-
nal to your script and, therefore, not directly accessible from it.
For example, when you open a file so that you can add contents to it, the underlying
code actually uses the operating system’s functionality to create a file descriptor that can
later be used for manipulating the file.This description can only be accessed by the func-
tionality that is built into the interpreter and is, therefore, embedded in a resource value
for your script to pass when taking advantage of the proper functionality.
Identifiers, Constants, and Variables
One of the most important aspects of any language is the capability to distinguish
between its various components.To ensure that the interpreter is capable of recognizing
each token of information passed to it properly, rules must be established for the purpose
of being capable to tell each portion apart from the others.
In PHP, the individual tokens are separated from each other through “whitespace”
characters, such as the space, tab, and newline character. Outside of strings, these charac-
ters have no semantic meaning—therefore, you can separate tokens with an arbitrary
number of them.With one notable exception that we’ll see in the next section, all
tokens are not case sensitive—that is, echo is equivalent to Echo, or even eCHo.
Identifiers, which, as their name implies, are used as a label to identify data elements
or groups of commands, must be named as follows:
n
The first character can either be a letter or an underscore.
n
Characters following the second can be an arbitrary combination of letters, digits,
and underscores.
Thus, for example, the following are all valid identifiers:
n
__anidentifier
n
yet_another_identifier___
n
_3_stepsToSuccess
Variables
As you can imagine, a language wouldn’t be very useful if all it could deal with were
immediate values: Using it would be a bit like buying a car with no doors or windows—
sure, it can run fast, but to what purpose?
Similar to almost every computer language, PHP provides a facility known as a “vari-
able” capable of containing data. PHP variables can contain one value at a time
(although that value could, for example, be an array, which itself is a container for an
arbitrary number of other values).
02 7090 ch01 7/16/04 8:44 AM Page 12
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
13
Identifiers, Constants, and Variables
Variables are identifiers preceded by a dollar sign ($).Therefore, they must respect all
the rules that determine how an identifier can be named. Additionally, variable names are
case sensitive, so $myvar is different from $MyVar.
Unlike other languages, PHP does not require that the variables used by a script be
declared before they can be used.The interpreter will create variables as they are used
throughout the script.
Although this translates in a high degree of flexibility and generally nimbler scripts, it
can also cause plenty of frustration and security issues. A simple spelling mistake, for
example, could turn a reference to $myvar to, say, $mvvar, thus causing your script to ref-
erence a variable that doesn’t exist. Similarly, if the installation of PHP that you are run-
ning has register_globals set to true, a malicious user will be able to set variables in
your script to arbitrary values unless you take the proper precautions—more about that
later in this chapter.
Variable Substitution in Strings
Both the double-quote and heredoc syntaxes support the ability to embed the value of a
variable directly in a string:
“The value of \$a is $a”
In the preceding string, the second instance of $a will actually be replaced by the value
of the $a variable, whereas the first instance will not because the dollar sign is escaped by
a backslash.
For those cases in which this simple syntax won’t work, such as when there is no
whitespace between the name of the variable whose value you want to extract and the
remainder of the string, you can forcefully isolate the data to be replaced by using braces:
<?
$thousands = 100;
echo “There are {$thousands}000 values”;
?>
Statements
A statement corresponds to one command that the interpreter must execute.This could
be an expression, a call to another block of code, or one of several constructs that PHP
defines. For example, the echo construct causes the value of an expression to be sent to
the script’s output device.
Statements always end in a semicolon—if they don’t, the system will output a parsing
error.
02 7090 ch01 7/16/04 8:44 AM Page 13
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
14
Chapter 1 The Basics of PHP
Constants
As their name implies, constants are data holders whose type and value doesn’t change.
A constant is create by using the define() construct. Here’s an example:
<?php
define (“SOME_CONSTANT”, 28);
echo SOME_CONSTANT;
?>
As you can see, define() takes two parameters; the first, a string, indicates the name of
the constant, whereas the second indicates its value. After you have defined a constant,
you can use it directly from your code, as we have done here.This means that although,
in theory, you can define a constant with an arbitrary name, you will only be able to use
it if that name follows the identifier naming rules that we discussed in the previous
sections.
Operators
Variables, constants, and data types are not very useful if you can’t combine and manipu-
late them in a variety of ways. In PHP, one of these ways is through operators.
PHP recognizes several classes of operators, depending on what purpose they are
used for.
The Assignment Operator
The assignment operator = is used to assign a value to a variable:
$a = 10;
$c = “Greetings Professor Faulken”;
$test = false;
It’s very important to understand that, by default, variables are assigned by value.This
means that the following
$a = $b
Assigns the value of $b to $a. If you change $b after the assignment has taken place, $a
will remain the same.This might not always be what you actually want to happen—you
might need to link $a and $b so that a change to the latter is also reflected in the latter.
You can do so by assigning to $a a reference to $b:
$a = &$b
Any change to $b will now also be reflected in $a.
02 7090 ch01 7/16/04 8:44 AM Page 14
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
15
Operators
Arithmetic Operators
Perhaps the class of operators that most newcomers to PHP most readily identify with is
the one that includes arithmetic operations.These are all part of binary operations
(meaning that they always include two operators):
n
Addition (+)
n
Subtraction (-)
n
Multiplication (*)
n
Division (/)
n
Modulus (%)
Operations are written using the infix notation that we are all used to. For example,
5 + 4
2 * $a
Keep in mind that the modulus operation works a bit different from the typical mathe-
matical operation because it returns a signed value rather than an absolute one.
PHP also borrows four special incrementing/decrementing operators from the C
language:
n
The prefix incrementing operator ++ increments the value of the variable that suc-
ceeds it, and then returns its new value. For example, ++$a
n
The postfix incrementing operator ++ returns the value of the variable that pre-
cedes it, and then increments its value. For example, $a++
n
The prefix decrementing operator — decrements the value of the variable that suc-
ceeds it, and then returns its new value. For example, —$a
n
The postfix decrementing operator — returns the value of the variable that pre-
cedes it, and then decrements its value. For example, $a—
The difference between the prefix and postfix version of the operators is sometimes dif-
ficult to grasp, but generally speaking is quite simple:The prefix version changes the
value of the variable first, and then returns its value.This means that if the value of $a is
1, ++$a will first increment $a by one, and then return its value (which will be 2).
Conversely, the postfix version returns the value first and then modifies it—so, if $a is 1,
$a++ will first return 1 and then increment $a to 2.
Unary incrementing and decrementing operations can be extremely helpful because
they enable for the modification of a variable in an atomic way and can easily be com-
bined with other operations. However, this doesn’t mean that they should be abused, as
they can make the code more difficult to read.
02 7090 ch01 7/16/04 8:44 AM Page 15
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
16
Chapter 1 The Basics of PHP
Bitwise Operators
This class of operators manipulates the value of variables at the bit level:
n
The bitwise AND (&)operation causes the value of a bit to be set if it is set in both
the left and right operands. For example, 1 & 1 = 1, whereas 1 & 2 = 0.
n
The bitwise OR (|) operation causes the value of a bit to be set if it is set in
either the left or right operands. For example, 1 | 1 = 1 and 1 | 2 = 3.
n
The bitwise XOR (^) operation causes the value of a bit to be set if it is set in
either the left or right operands, but not in both. For example, 1 ^ 1 = 0, 1 ^ 0
= 1.
n
The bitwise NOT (~)operation causes the bits in its operand to be reversed—that
is, set if they are not and unset otherwise. Keep in mind that if you’re dealing with
an integer number, all the bits of that integer number will be reversed providing a
value that you might not expect. For example, on a 32-bit IBM platform, where
each integer is represented by a single 32-bit value, ~0 = -1, because the integer is
signed.
n
The bitwise left-shift (<<) and right-shift (>>) operators actually shift the bits of
the left operands left or right by the number of positions specified by the right
operand. For example, 4 >> 1 = 2, whereas 2 << 1 = 4. On integer values, shift-
ing bits to the left by n positions corresponds to multiplying the left operand by
2
n
, whereas shifting them right by n position corresponds to dividing the left
operand by 2
n
.
Remember that bitwise operations can only be performed on integer values. If you use a
value of a different type, PHP will convert it for you as appropriate or output an error if
it can’t.
Error-control Operators
PHP is normally very vocal when it finds something wrong with the code it’s interpret-
ing and executing, outputting verbose and helpful error messages to mark the occasion.
Sometimes, however, it’s practical to ensure that no error be reported, even if an error
condition occurs.
This can be accomplished by using the error-suppression operator @ in front of the
operation you want to perform. For example, the following would normally print an
error because the result of a division by zero is infinity—a number that cannot be repre-
sented by any of the PHP data types.With the @ operator, however, we can prevent the
error from being printed out (but not from occurring):
<?php
@$a = 1 / 0;
?>
02 7090 ch01 7/16/04 8:44 AM Page 16
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
17
Operators
This operator can be very dangerous because it prevents PHP from notifying you that
something has gone wrong.You should, therefore, use it only whenever you want to pre-
vent errors from propagating to a default handler because you have a specialized code
segment that you want to take care of the problem. Generally speaking, it’s a bad idea to
use this approach simply as a way to “silence” the PHP interpreter, as there are better
ways to do so (for example, through error logging) without compromising its error
reporting capabilities.
Note that not all types of errors can be caught and suppressed using the @ operator.
Because PHP first parses your script into an intermediate language that makes execution
faster and then executes it, it won’t be capable of knowing that you have requested error
suppression until the parsing phase is over and the execution phase begins. As a result,
syntax errors that take place during the parsing phase will always result in an error being
outputted, unless you have changed your php.ini settings in a way that prevents all errors
from being outputted independently from your use of the @ operator.
String Operators
When it comes to manipulating strings, the only operator available is the concatenation
operator, identified by a period (.). As you might imagine, it concatenates two strings
into a third one, which is returned as the operation’s result:
<?php
$a = ‘This is string ‘;
$b = $a . “is complete now.”;
?>
Comparison Operators
Comparison operators are used to determine the relationship between two operands.
The result of a comparison is always a Boolean value:
n
The == operator determines if two values are equal. For example, 10 == 10
n
The != operator determines if two values are different. For example, 10 != 11
n
The < operator determines whether the left operand’s value is less than the right
operand’s.
n
The > operator determines whether the left operand’s value is greater than the
right operand’s.
n
The <= operator determines whether the left operand’s value is less than or equal
to the right operand’s.
n
The >= operator determines whether the left operand’s value is greater than the
right operand’s.
02 7090 ch01 7/16/04 8:44 AM Page 17
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Không có nhận xét nào:
Đăng nhận xét