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

The most important thing to remember when sending headers from

PHP is that all of the headers must be sent prior to any Web content.

If even a single character of the Web page is sent prior to sending

the header, the header information will be considered text within

the Web page and not header information. This will prevent your file

from being downloaded. The easiest way to avoid this problem is to

ensure that the first characters on the first line of the PHP script are

the opening PHP tag (<?php).

PHP uses the header() function to return header information to the

client Web browser. The header() function takes a single parameter,

which is a text string containing the name of the header field followed

by a colon, a space, and the data to associate with the header. The

headers listed in Table 5-7 are far from comprehensive, but they are

the only ones you need to download a file.

For example, the following headers tell the Web browser that a file

named info.doc is 5000 bytes long, is encoded using base64 encoding,

and is a file being downloaded:


CHAPTER 5

Working with Files and Directories

header("Content-Description: File Transfer");

header("Content-Type: application/force-download");

header("Content-Disposition: attachment;

filename=\"info.doc\"");

header("Content-Transfer-Encoding: base64");

header("Content-Length: 5000");

254

The “Content-Type” header can be used in two ways. If you want the

downloaded file to appear in the client’s Web browser as if it were a

normal file, use the MIME type for the file. For example, if you are

downloading a JPEG image, the MIME type would be “image/jpeg”.

The Web browser will display the image. If you want the file to be

saved to the user’s hard drive instead of being opened in the Web

browser, use a MIME type of “application/force-download”, which

instructs the Web browser to open a “save file” dialog box and write

the file to disk.

The third step, once the headers have been sent, is to send the file

itself. The PHP readfile() function reads a file from disk and sends

it directly to the Web browser. The only required parameter for the

readfile() function is a string containing the path and filename to

the file being sent; on success, readfile() returns the number of bytes

sent; on failure, readfile() returns FALSE.

readfile("/usr/uploads/info.doc");

You are finished when the headers have been sent and the readfile()

function has sent the file’s contents. Do not send any XHTML data,

or it will become part of the downloaded file information. If, however,

the headers were not sent and the readfile() function was not called,

the PHP script can create a Web page explaining that the file could

not be downloaded and why. Therefore, your code should ensure that

the headers were not sent and the readfile() function was not called

prior to sending the Web page output.

To create a PHP downloader for the files subdirectory:

1.

2.

Create a new document in your text editor.

Add the following script section to the document body. Be sure

that there is nothing in the file before the opening PHP tag:

<?php

?>

3.

Add the following code to the script section to check if the

requested file exists and is readable:

$Dir = "files";

if (isset($_GET['filename'])) {

$FileToGet = $Dir . "/" . stripslashes

($_GET['filename']);


Uploading and Downloading Files

if (is_readable($FileToGet)) {

}

else {

$ErrorMsg = "Cannot read \"$FileToGet\"";

$ShowErrorPage = TRUE;

}

}

else {

$ErrorMsg = "No filename specified";

$ShowErrorPage = TRUE;

}

if ($ShowErrorPage) {

255

4.

Add the following code in the if section of the inner

if...else statement for the is_readable() test to download

the file:

header("Content-Description: File Transfer");

header("Content-Type: application/force-download");

header("Content-Disposition: attachment;

filename=\"" . $_GET['filename'] . "\"");

header("Content-Transfer-Encoding: base64");

header("Content-Length: " . filesize($FileToGet));

readfile($FileToGet);

$ShowErrorPage = FALSE;

5.

Add the following code immediately after the closing PHP tag

to show the error page. Note the use of advanced escaping to

display the Web page output.

<!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>File Download Error</title>

<meta http-equiv="content-type" content="text/html;

charset=iso-8859-1" />

</head>

<body>

<p>There was an error downloading "<?php echo

htmlentities($_GET['filename']); ?>"</p>

<p><?php echo htmlentities($ErrorMsg); ?></p>

</body>

</html>

<?php

}

?>

6.

Save the document as FileDownloader.php in the Chapter

directory for Chapter 5 and upload the file to the server.

Reopen ViewFiles.php. Replace the line that reads:

echo "<a href=\"$FullEntryName\">" .

htmlentities($Entry). "</a>\n";

7.


CHAPTER 5

Working with Files and Directories

with a line that reads:

echo "<a

href=\"FileDownloader.php?filename=$Entry\">" .

htmlentities($Entry). "</a>\n";

8.

256

9.

Save ViewFiles.php and upload the file to the Web server.

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

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

ter.05/Chapter/ViewFiles.php. Click one of the highlighted

filenames. Your Web browser should display a “save file”

dialog box like the one shown in Figure 5-8. Save the file and

verify that it downloaded correctly.

Figure 5-8

The “save file” dialog box for polarbear.gif

10. Close your Web browser window.

Short Quiz

1.

What type of form input element is used to choose the file to

upload?

What hidden form input element restricts the size of the

uploaded file?

What is the name of the autoglobal array that contains the

uploaded file information?

2.

3.


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