Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

The PHP Group officially recommends that you use standard PHP

script delimiters to write PHP code declaration blocks. One reason

Is that standard php script delimiters are guaranteed to be available

on any Web server that supports PHP. (As you will learn shortly, both

short PHP script delimiters and ASP-style script delimiters can be

disabled.) However, the primary reason for using standard PHP script

delimiters is that they are the only method that is completely compli-

ant with XML. (The Web page examples and exercises in this book

are written in XHTML, which is based on XML.) XML is preferred

for Web development not only because it is the basis of XHTML

documents, but because it has become the standard for exchanging

data on the Internet. For this reason, you should always ensure that

any Web pages or scripts you create are compliant with XML.


Creating PHP Code Blocks

Even though the PHP Group officially recommends that you use stan-

dard PHP script delimiters to write PHP, some Web developers prefer

the other types of code declaration blocks, so you should be able to

recognize the other delimiters when you see them.

To create a PHP script that contains standard PHP script delimiters:

1.

2.

5

Create a new document in your text editor.

Type the <!DOCTYPE> declaration, <html> element, header

information, and <body> element. Use the strict DTD and

“PHP Code Blocks” as the content of the

<title> element.

Your document should appear as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>PHP Code Blocks</title>

<meta http-equiv="content-type"

content="text/html; charset=iso-8859-1" />

</head>

<body>

</body>

</html>

3.

Add the following paragraph element and standard PHP

script delimiters to the document body. Be sure to nest the

script delimiters within the paragraph element. The paragraph

element forces the output from the script delimiters to render

on a separate line.

<p>

<?php

?>

</p>

4.

Add the following echo statement (shown in bold) between

the script delimiters:

<p>

<?php

echo "This text is displayed using standard PHP

script delimiters. ";

?>

</p>

5.

Save the document as PHPCodeBlocks.php in the Chapter

directory for Chapter 1. Be sure to use an extension of .php,

which is required for your Web server to recognize the file as

a PHP script.


CHAPTER 1

Getting Started with PHP

6.

Use FTP to upload the PHPCodeBlocks.php file to the Web

server. Once you have successfully uploaded the docu-

ment, validate it with the W3C XHTML Validator at http://

validator.w3.org/. (Instructions for validating XHTML

documents are included in Appendix A.)

Open the PHPCodeBlocks.php file in your Web browser

by entering the following URL: http://<yourserver>/

PHP_Projects/Chapter.01/Chapter/PHPCodeBlocks.php

(replacing <yourserver> with the name of the Web server

provided by your instructor). You should see the Web page

shown in Figure 1-1.

6

7.

Figure 1-1

Output of a PHP script with standard PHP script delimiters

8.

Close your Web browser window.

The <script> Element

A second option for creating PHP code blocks is to use the XHTML

<script> element. When the <script> element is used with PHP,

you must assign a value of “php” to the language attribute of the

<script> element to identify the code block as PHP. When the PHP

scripting engine encounters a <script> element with “php” assigned

to its language attribute, it processes any code within the element

as PHP on the server before returning the Web page. The syntax for

using PHP with the <script> element is as follows:

<script language="php">

statements;

</script>

The following example contains the same echo statement you saw

with the standard PHP script delimiters, but this time the statement

is contained within a PHP <script> element:

<script language="php">

echo "Explore Africa!";

</script>

Creating PHP Code Blocks

Like the standard PHP script delimiters, the <script> element is

always available on any Web server that supports PHP. Unfortunately,

the <script> element’s language attribute is deprecated in XHTML.

Further, the scripting engine ignores <script> elements that include

the type attribute, which is required for compatibility with both the

strict and transitional DTDs. For this reason, you cannot validate

documents that include PHP <script> elements.

To add a PHP <script> element to the PHPCodeBlocks.php

document:

1.

7

Return to the PHPCodeBlocks.php document in your text

editor.

Add the following paragraph element and <script> element

to the end of the document body:

<p>

<script language="php">

</script>

</p>

2.

3.

Add the following echo statement (shown in bold) between

the script delimiters:

<p>

<script language="php">

echo "This text is displayed using a PHP script

section.";

</script>

</p>

4.

Save the PHPCodeBlocks.php document, upload it to the

Web server, and then open it from your Web server. Your

Web browser should appear similar to Figure 1-2.

Figure 1-2

5.

Output of a PHP script after adding a PHP script section

Close your Web browser window.

CHAPTER 1

Getting Started with PHP

Short PHP Script Delimiters

A simplified method of writing PHP code declaration blocks is to use

the short <? and ?> script delimiters. Short PHP script delimiters are

similar to standard PHP script delimiters, except they do not include

‘php’ in the opening delimiter. The syntax for short PHP script delim-

iters is as follows:

<? statements; ?>

8

The following example shows how to use short delimiters with the

echo statement you saw earlier:

<? echo "Explore Africa!"; ?>

Unlike the <?php and ?> script delimiters and the <script> element,

which are always available on any Web server that supports PHP, the

short <? and ?> delimiters can be disabled in a Web server’s php.ini

configuration file. Because a Web server on which your PHP script

will run might not always be under your control, the PHP Group

discourages the use of short delimiters, especially when developing

scripts that will be redistributed and used by other Web develop-

ers. Although you can use short PHP script delimiters if you prefer,

your PHP scripts will not work if your Web site is hosted by an ISP

that does not support short PHP script delimiters. Another reason to

avoid the short <? and ?> delimiters is that you cannot use them in

XML documents, although you can use them in XHTML documents,

including documents that conform to the strict DTD. With XML

documents, you must use the <?php and ?> script delimiters.

To add short PHP script delimiters to the PHPCodeBlocks.php

document:

1.

Return to the PHPCodeBlocks.php document in your text

editor.

Add the following paragraph element and short PHP script

delimiters to the end of the document body:

<p>

<?

?>

</p>

2.

3.

Add the following echo statement (highlighted in bold)

between the script delimiters:

<p>

<?

echo "This text is displayed using short PHP

script delimiters.";

?>

</p>


Creating PHP Code Blocks

4.

Save the PHPCodeBlocks.php document, upload it, and open

it from your Web server. Your Web browser should appear

similar to Figure 1-3.

9

Figure 1-3

5.

Output of a PHP script after adding short PHP script delimiters

Close your Web browser window.

ASP-Style Script Delimiters

Some Web developers prefer to use the ASP-style script delimiters of

<% and %> to develop PHP scripts. The syntax for ASP-style script

delimiters is similar to that of short PHP script delimiters, as follows:

<% statements; %>

The following example shows how to use ASP-style script delimiters

with the echo statement you saw earlier:

<% echo "Explore Africa!"; %>

Like short PHP script delimiters, ASP-style script delimiters are com-

pliant with XHTML, including the strict DTD, but not with XML.

ASP-style script delimiters can also be enabled or disabled in the

php.ini configuration file, so you should not use them unless you are

sure they are enabled on any Web servers on which your PHP scripts

will run. Unless you are a hard-core ASP developer who only uses

PHP occasionally, or if you are using an HTML editor that does not

support PHP script delimiters, there is little reason to use ASP-style

script delimiters.

To add ASP-style script delimiters to the PHPCodeBlocks.php

document:

1.

Return to the PHPCodeBlocks.php document in your text

editor.

CHAPTER 1

Getting Started with PHP

2.

Add the following paragraph element and ASP-style script

delimiters to the end of the document body:

<p>

<%

%>

</p>

10

3.

Add the following echo statement (shown in bold) between

the script delimiters:

<p>

<%

echo "This text is displayed using ASP-style

script delimiters.";

%>

</p>

4.

Save the PHPCodeBlocks.php document, upload it, and open

it from your Web server. Your Web browser should appear

similar to Figure 1-4.

Figure 1-4

Output of a PHP script after adding ASP-style script delimiters

5.

Close your Web browser window.

Understanding Functions

Before you start writing PHP scripts, you need to understand the

basics of functions. The term function refers to a subroutine (or

individual statements grouped into a logical unit) that performs a

specific task. PHP includes numerous built-in functions that perform

various types of tasks. You will work with many built-in PHP func-

tions throughout this book. To execute a function, you must invoke,

or call, it from somewhere in your script. The statement that calls a

function is referred to as a function call and consists of the function

name followed by any data that the function needs. The data (which

you place in parentheses following the function name) are called

Creating PHP Code Blocks

arguments or actual parameters. Sending data to a called function

is called passing arguments. Many functions generate, or return,

some sort of a value that you can use in your script. For example, PHP

includes a round() function that rounds a decimal value to the near-

est whole number. You pass a number as an argument to the round()

function, which calculates and returns the nearest whole number.

The following statement calls the round() function and passes to it

a value of 3.556. The round() function calculates and returns a value

of 4, which is then displayed with an echo statement.

<?php echo round(3.556); ?>

11

Many functions can accept multiple arguments, which you separate

with commas. For example, the second argument you pass to the

round() function determines the number of digits after the decimal

point that it should use to round the number. The following state-

ment calls the round() function and then passes to it a first argument

of 3.556 and a second argument of 2. The round() function calculates

and returns a value of 3.56 (rounded to two decimal places), which is

then displayed with an echo statement.

<?php echo round(3.556, 2); ?>

You learn more

about func-

tions, including

how to create

your own, in

Chapter 2.

To create a PHP script that uses the phpinfo() function to create a

Web page that lists diagnostic information for the current PHP con-

figuration on the Web server:

1.

2.

Create a new document in your text editor.

Type the <!DOCTYPE> declaration, <html> element, header

information, and <body> element. Use the strict DTD and “PHP

Diagnostic Information” as the content of the <title> element.

Add the following standard PHP script delimiters and

phpinfo() function to the document body. Be certain to

include the parentheses and semicolon in the statement con-

taining the phpinfo() function.

<?php

phpinfo();

?>

3.

4.

Save the document as PHPTest.php in the Chapter direc-

tory for Chapter 1 and upload the document to the Web

server. You will not be able to validate this page with the W3C

XHTML Validator because the phpinfo() function inserts a

second set of HTML headers.

Open the PHPTest.php file in your Web browser by entering

the following URL: http://<yourserver>/PHP_Projects/Chap-

ter.01/Chapter/PHPTest.php. You should see a Web page

5.

CHAPTER 1

Getting Started with PHP

similar to the one shown in Figure 1-5, which lists diagnostic

information for PHP.

12

Figure 1-5

PHP Diagnostic Information Web page

6.

Close your Web browser window.

Displaying Script Results

When you write a PHP script, you will often want to display the

results of the script in the Web page that is returned as a response

to a client. For example, you might want the Web page to display

database records that the client requested or the result of a calcula-

tion that was processed by the PHP script. Recall that the scripting

engine ignores any non-PHP code and only processes the PHP code

it finds within PHP code blocks. The Web server then returns the

Creating PHP Code Blocks

results of the PHP script and any HTML or XHTML elements found

in the PHP file to the client, where it is rendered by the client’s Web

browser. To return these script results to the client, you must use an

echo statement, which you’ve already seen, or the print statement.

The echo and print statements create new text on a Web page that

is returned as a response to a client.

You might be thinking that the echo and print statements are func-

tions. Actually, they are not functions, but language constructs of the

PHP programming language. A programming language construct

refers to a built-in feature of a programming language. The echo and

print statements are nearly identical, but they have some differences.

For example, the print statement returns a value of 1 if it is success-

ful or a value of 0 if it is not successful, while the echo statement does

not return a value. You need to learn a little more about functions

before you can understand why the print statement returns a value.

However, keep in mind that you can use the exact same syntax with

the print statement that you use with the echo statement.

To modify the PHPCodeBlocks.php document so it uses print state-

ments instead of echo statements:

1.

13

Return to the PHPCodeBlocks.php document in your text

editor.

Replace each of the echo statements with a print statement.

For example, the statement within the standard PHP script

delimiters should read as follows:

<?php

print "This text is displayed using standard PHP

script delimiters.";

?>

2.

3.

Save the PHPCodeBlocks.php document, upload it, and then

open it from your Web server. The document should render

the same as it did with the echo statements.

Close your Web browser window.

4.

You should understand that the only reason to use the echo and

print statements is to include the results of a PHP script within a

Web page that is returned to a client. For example, you might want

to return a new Web page based on information a user enters into a

form for an online transaction and submits to a Web server. You can

use a PHP script to process the submitted information and return a

new Web page to the client that displays the sales total, order con-

firmation, and so on. If you simply want to display text in a Web

page that is returned to the client, there is no need to use anything

but standard XHTML elements. The procedures for submitting and

CHAPTER 1

Getting Started with PHP

processing data are a little too complicated for this introductory

chapter. In this chapter, you use the echo and print statements to

return the results of a script to a client in order to learn the basics

of PHP.

14

For both the echo and print statements, you need to include a text

string that contains the text that will appear in the Web browser. A

literal string is text that is contained within double or single quota-

tion marks. As you saw earlier, the following echo statement uses

double quotation marks to display the text “Explore Africa!” in the

Web browser window:

<?php echo "Explore Africa!"; ?>

You can also use single quotation marks with the preceding echo

statement, as follows:

<?php echo 'Explore Africa!'; ?>

The echo and print statements support multiple arguments. If you

want to pass multiple arguments to the echo and print statements,

separate them with commas, just as with arguments passed to a func-

tion. In the following example, three text string arguments are passed

to the echo statement:

<?php echo "Explore Africa, ", "South America, ",

" and Australia!"; ?>

To create a script that passes multiple arguments to an echo

statement:

1.

2.

Create a new document in your text editor.

Type the <!DOCTYPE> declaration, <html> element, header

information, and <body> element. Use the strict DTD and

“How to Talk Like a Pirate” as the content of the

<title>

element.

Add the following heading element to the document body:

<h1>How to Talk Like a Pirate</h1>

3.

4.

Next, add paragraph tags and a standard PHP script delimiter

to the end of the document body:

<?php

?>

5.

Now add the following echo statement to the PHP code block:

echo "Avast me hearties! ",

"Return handsomely with some fine swag, ye

scurvy dogs! ",

"Else, we be keelhaulin' ye' next morn . . . ";


Creating PHP Code Blocks

6.

Save the document as PirateTalk.php in the Chapter direc-

tory for Chapter 1, and upload the document to the Web

server. After you upload the document, attempt to validate it

with the W3C XHTML Validator. You will get a “text is not

allowed here” error, which you will fix in a later exercise.

Open the PirateTalk.php file from your Web server by enter-

ing the following URL: http://<yourserver>/PHP_Projects/

Chapter.01/Chapter/PirateTalk.php. Your Web browser

should appear similar to Figure 1-6.

15

7.

Figure 1-6

“How to Talk Like a Pirate” Web page

8. Close your Web browser window.

You can also use parentheses with the echo and print statements in

the same manner that you use them with functions, as follows:

<?php echo("Explore Africa, ", "South America, ",

" and Australia!"); ?>

You will not use parentheses with most of the echo and print state-

ments you write in this book. However, you should be able to recog-

nize the parenthesized version as just another form of the echo and

print statements, not a separate type of function.

So far, the arguments you have seen and used with the echo state-

ments have consisted of plain text that is rendered in the Web

browser’s default font. To format the output of text that is displayed

with echo and print statements, you can use any XHTML formatting

elements you want as part of the text string arguments. The following

code shows a modified version of the previous script, but this time

the echo statement includes several XHTML elements to format the

appearance of the text string in a Web browser. Figure 1-7 shows how

the script is rendered in a Web browser.

<?php echo "<p>Explore <strong>Africa</strong>, <br />",

"<strong>South America</strong>, <br />",

" and <strong>Australia</strong>!</p>"; ?>


CHAPTER 1

Getting Started with PHP

16

Figure 1-7 Output of an echo statement

with XHTML elements

To modify the PirateTalk.php script so the echo statement includes

XHTML elements:

1.

2.

Return to the PirateTalk.php script in your text editor.

Modify the values passed to the echo statement so they

include paragraph and line break elements, as follows:

echo "<p>Avast me hearties!<br />",

"Return handsomely with some fine swag,<br />ye

scurvy dogs!<br />",

"Else, we be keelhaulin' ye' next morn . . . </p>";

You study

additional

techniques for

working with

text strings in

Chapter 3.

3.

Save the PirateTalk.php file and upload it to the Web server.

Validate the document with the W3C XHTML Validator (the

error should be gone now), and then open the document from

your Web server. The document should appear similar to

Figure 1-8.

Figure 1-8 “How to Talk Like a Pirate” Web page after adding XHTML elements to the

echo statement

4. Close your Web browser window.


Creating PHP Code Blocks

Creating Multiple Code Declaration Blocks

You can include as many PHP script sections as you want within a

document. However, when you include multiple script sections in a

document, you must include a separate code declaration block for

each section. The following document includes two separate script

sections. The script sections create the information that is displayed

beneath the <h2> heading elements.

...

</head>

<body>

<h1>Multiple Script Sections</h1>

<h2>First Script Section</h2>

<?php echo "<p>Output from the first script

section.</p>"; ?>

<h2>Second Script Section</h2>

<?php echo "<p>Output from the second script

section.</p>"; ?>

</body>

</html>

17

Remember that PHP code declaration blocks execute on a Web server

before a Web page is sent to a client. If users were to view the source

document after they received the PHP document, they would not

see any PHP code declaration blocks. Instead, the users would only

see the results returned from the PHP code. The following example

shows how the source code for the preceding document appears after

a user receives it. Notice that the PHP code declaration blocks have

been converted to elements and text. Figure 1-9 shows how the text

and elements appear in a Web browser.

...

</head>

<body>

<h1>Multiple Script Sections</h1>

<h2>First Script Section</h2>

<p>Output from the first script section.</p>

<h2>Second Script Section</h2>

<p>Output from the second script section.</p>

</body>

</html>

CHAPTER 1

Getting Started with PHP

18

Figure 1-9

Output of a document with two PHP script sections

Even though many people may enjoy talking like a pirate, the

PirateTalk.php document is of limited use in demonstrating how

to write PHP scripts. Therefore, in the next exercise, you will write

a PHP script that displays the results of several built-in PHP func-

tions using multiple script sections. You will use the phpversion(),

zend_version(), and ini_get() functions. The phpversion() func-

tion returns the version of PHP that processed the current page. The

zend_version() function returns the version number of the Zend

Engine, which is PHP’s scripting engine. The ini_get() function

returns the value assigned to a directive in the php.ini configuration

file. You need to pass the name of a directive to the ini_get() func-

tion, surrounded by quotation marks.

To create a script with multiple script sections:

1.

2.

Create a new document in your text editor.

Type the <!DOCTYPE> declaration, <html> element, header

information, and <body> element. Use the strict DTD and

“PHP Environment Info” as the content of the

<title>

element.

Add the following heading element to the document body:

<h1>PHP Environment Info</h1>

3.


Creating PHP Code Blocks

4.

Add the following elements, text, and PHP code block to the

document body. The code block displays the PHP version

number using the phpversion() function.

<p>This page was rendered with PHP version

<?php

echo phpversion();

?>.

</p>

19

5.

Add the following elements, text, and PHP code block to the

end of the document body. The code block displays the Zend

Engine version number using the zend_version() function.

<p>The PHP code was rendered with Zend Engine

version

<?php

echo zend_version();

?>.

</p>

6.

Finally, add the following elements, text, and PHP code blocks

to the end of the document body. The code blocks use the

ini_get() function to display PHP’s default MIME type and

the maximum amount of time that a PHP script is allowed to

execute.

<p>PHP's default MIME type is

<?php

echo ini_get("default_mimetype");

?>.

</p>

<p>The maximum allowed execution time of a PHP

script is

<?php

echo ini_get("max_execution_time");

?>

seconds.</p>

7.

Save the document as MultipleScripts.php in the Chapter

directory for Chapter 1. After you save and upload the docu-

ment, validate it with the W3C XHTML Validator.

Open the MultipleScripts.php file from your Web server

by entering the following URL: http://<yourserver>/

PHP_Projects/Chapter.01/Chapter/MultipleScripts.php.

Your Web browser should appear similar to Figure 1-10.

8.

CHAPTER 1

Getting Started with PHP

20

Figure 1-10

Web page with multiple PHP scripts

9. Close your Web browser window.

Case Sensitivity in PHP

Unlike XHTML and JavaScript, programming language constructs in

PHP are mostly case insensitive, although there are some exceptions.

This means that you can use any of the following versions of the echo

statement without receiving an error message:

<?php

echo "<p>Explore <strong>Africa</strong>, <br />";

Echo "<strong>South America</strong>, <br />";

ECHO " and <strong>Australia</strong>!</p>";

?>

Exceptions

to PHP’s

case insensi-

tivity include

variable and

constant

names, which are case

sensitive. You will study

variables and constants

later in this chapter.

Even though you can use whatever case you want, be certain to use

the letter cases presented in this book for consistency and to make it

easier to locate any problems in your scripts.

Adding Comments to a PHP Script

When you write a script, whether in PHP or any other programming

language, it is considered good programming practice to add com-

ments to your code. Comments are lines you place in your code that

do not get executed, but provide helpful information. Comments

include the name of the script, your name and the date you created

the program, notes to yourself, or instructions to future programmers

who might need to modify your work. When you are working with

long scripts, comments make it easier to understand how a program

is structured.


Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]