copyright © 2003 pearson education, inc. slide 6b-1 the web wizards guide to php by david lash

33
Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizard’s Guide to PHP by David Lash

Upload: hayden-lyons

Post on 26-Mar-2015

214 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-1

The Web Wizard’s Guide to PHPby David Lash

Page 2: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-2

CHAPTER 6Working with Files:

Using files on the Web Server From PHP Scripts

Page 3: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc.

Objectives To learn to work with files to store and retrieve

data To understand the types of applications that can

use File I/O

Page 4: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-4

Why Use Files Files can provide an easy mechanism for storing

data between executions of scripts: store customer data store page hit counts remember end-user preferences store product inventory

Page 5: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-5

Reading A file the easy way. You can use the file() function to read an entire

file into a PHP array Each array item will be assign 1 line For example:

$inf ='mydata.txt'; $infile = file ($inf); print "$infile[0]";

print "$infile[2]";

Open mydata.txt and read into $infile array.

Output the1st and then 3rd line of mydata.txt

Page 6: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-6

So if mydata.txt was stored in same directory at your PHP script and contained:

Apples are red.Bananas are yellow.Carrots are orange.Dates are brown.

Would output:Apples are red.

Carrots are orange. Using file() works well but does consume memory

Can slow scripts down for large files

Reading A file the easy way.

Page 7: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-7

Using fopen() to open files

Use the fopen() script to create a connection to a file once connected can read or write a line at a

time

$file_ptr = fopen ($fileloc, 'r');

The filename of the file on the web server.

A file handle used to refer to the file in your program.

$fileloc = '/home/phppgm/data/data.txt';

File open mode.("r" means read only)

Page 8: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-8

Using file open mods

Table 6.3 File Open Modes for Use with the fopen() Function

Open Mode

Description

r Read-only mode opens the file for reading but not writing.

r+ Read and write mode opens the file for reading and writing.

w Write-only mode opens a file for writing. If the file exists, it overwrites the existing file when writing. If the file doesn’t exist, it creates a new file.

w+ Read and write overwrite mode opens the file for writing and reading. If the file exists, it overwrites the existing file when writing.. If the file doesn’t exist, it creates a new file.

a Append mode opens the file for writing but will append any data written to the end of the existing file. If the file doesn’t exist, this command creates a new file.

a+ Read and append mode opens the file for writing and reading. Any written data is appended to the existing file. If the file doesn’t exist, writing data will create a new file.

Page 9: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-9

Dealing with fopen() failure

The fopen() function can fail for a number of reasons: file location, file permissions, corrupt file

Provide an option for fopen() to output a message if it fails:

$inf = '/home/phppgm/data/mydata.txt'; $FILEH = fopen($inf, 'r') or die ("Cannot open $inf");

Only run die() when fopen()fails.

Page 10: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-10

Using fgets() to read

Open you open a file for reading use fgets() to read it:

$var = fgets(filehandle, length);

The filehandle of thefile used in the fopen()function.

Optional argument thatindicates one more thanthe maximum numberof bytes to read.

Variable will receive thecharacters read from thefile.

Page 11: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-11

A Full Script Example Consider an example script that invites end-user to select

product number: Provides information about the product. Uses the following HTML form input line:

<input type="radio" name="id" value=$item>

Also uses the following input file: AC1000:Hammers:122:12.50AC1001:Wrenches:5:5.00AC1002:Handsaws:10:10.00AC1003:Screwdrivers:222:3.00

Page 12: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-12

PHP Script1. <html><head><title>Hardware Inventory</title> </head><body>2. <font SIZE =5 color=blue> Happy Harry's Hardware Inventory 3. <br></font><?php4. $inf='/home/phppgm/data/infile.txt';5. $FILEH = fopen($inf, 'r') or die ("Cannot open $inf");6. $inline = fgets($FILEH, 4096);7. $found=0;8. while (!feof($FILEH) && !($found)) {9. list($ptno,$ptname,$num,$price) = split (':',$inline);10. if ($ptno == $id) {11. print '<table border=1>';12. print '<th> ID <th> Part <th> Count <th> Price ';13. print "<tr><td> $ptno </td><td>$ptname</td>";14. print "<td> $num </td><td>\$$price</td></tr>";15. print '</table>';16. $found = 1;17. }18. $inline = fgets($FILEH, 4096);19. }20. if ($found != 1) {21. print "Error: PartNo=$id not found";22. }23. fclose ($FILEH);24. ?></body></html>

Page 13: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-13

PHP Script With REGISTER_GLOBALS Off1. <html><head><title>Hardware Inventory</title> </head><body>2. <font SIZE =5 color=blue> Happy Harry's Hardware Inventory 3. <br></font><?php $id = $_POST = [“id”];4. $inf='/home/phppgm/data/infile.txt';5. $FILEH = fopen($inf, 'r') or die ("Cannot open $inf");6. $inline = fgets($FILEH, 4096);7. $found=0;8. while (!feof($FILEH) && !($found)) {9. list($ptno,$ptname,$num,$price) = split (':',$inline);10. if ($ptno == $id) {11. print '<table border=1>';12. print '<th> ID <th> Part <th> Count <th> Price ';13. print "<tr><td> $ptno </td><td>$ptname</td>";14. print "<td> $num </td><td>\$$price</td></tr>";15. print '</table>';16. $found = 1;17. }18. $inline = fgets($FILEH, 4096);19. }20. if ($found != 1) {21. print "Error: PartNo=$id not found";22. }23. fclose ($FILEH);24. ?></body></html>

Page 14: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-14

The Output ...

The previous code can be executed at http://webwizard.aw.com/~phppgm/C6/drive_invent.php

Page 15: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-15

Writing to Files

You can use the fputs() function

The above outputs: “My script was here” into the file that $OFILE points to

The filehandle of the file to writeto.

Returns numberof bytes written or false(0) ifan error.

$message = "My script was here";$ret = fputs($OFILE, $message);

The data to output.

Page 16: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-16

Putting it all together

Consider the following script that: opens a file, writes one line to it closes the file

$inf ='/home/phppgm/data/log.txt'; $FILEH = fopen($inf, 'w') or die("Cannot open $inf"); fputs($FILEH, 'Apples are red');

fclose ($FILEH);

Page 17: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-17

A Full Script Example

Consider another example that appends end-user comments to the end of a file: Asks end-user for comments about site. Uses the following HTML form input line:

<br><textarea rows="1" cols="50" name="comments"></textarea>

Page 18: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-18

PHP Script

1. <html> <head><title>Log Comments</title></head> <body>2.<?php3. $logfile='/home/phppgm/data/comments.txt';4. $OUTF = fopen($logfile, 'a+') or die("Cannot open $logfile");5. $today = date('m/d/Y:h:m');6. $msg = "$today:$comments\n";7. print "Just Logged: <br> $msg";8. fputs($OUTF, $msg);9. fclose($OUTF);10.?>

11. </body></html>

Page 19: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-19

Locking a File

Web application have potential for many users to execute same script at same time If scripts attempt to write the same file at

same instance in time, may corrupt the file A corrupted file is a useless unintelligible

mixture of data.

Page 20: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-20

Using flock

PHP provide a flock() function that can ensure only 1 script at a time writes to a file. Use it in your scripts as a defense against file

corruption

File handle that indicates whatfile to lock.

Returns false (0) ifnot successful.

$ret = flock($FHILE, LOCK_EX);Lock type: LOCK_EX meansonly 1 program can read/writeto file at a time.

Page 21: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-21

Tip: Using the newline character \n

Use the \n character to output a new line character into the file. If you omit the new line character, the appended text will appear together on the same line if you run the script twice, for example:

My script was hereMy script was here

If your script puts an \n at the lines’ end:

My script was here

My script was here

Page 22: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-22

Reading and Writing Files

When reading and writing from same file can use the rewind() function: Resets the file pointer to start of file:

$ret = rewind(filehandle); For example consider:

1. $FILEH = fopen('myfile.txt', 'r+');2. $inline = fgets($FILEH, 4096);3. rewind($FILEH);

4.$ret= fputs($FILEH, 'Z');

Page 23: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-23

Reading and Writing Files For example consider:

1. $FILEH = fopen('myfile.txt', 'r+');2. $inline = fgets($FILEH, 4096);3. rewind($FILEH);4.$ret= fputs($FILEH, 'Z');

Suppose myfile.txt contains:ABC

After script segment runs, the file will contain: ZBC

Page 24: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-24

A Full Script Example

Consider a script that implements a web page hit counter: Use counter file at /home/phppgm/logfiles/ctr.txt.

Can place into this file and access it as:

<?php include 'counter.php' ?>

Page 25: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-25

A Full Script Example: Accessing the counter

Can place into this file and access it as:

<?php include 'counter.php' ?>

For example: <html><head><title>Harry's Place </title></head><body><font size=5 color=blue>Happy Harry's Hardware Home</font>

<br>Hit Count:<?php include 'counter.php' ?>

</body></html>

Page 26: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-26

PHP Script

1. <?php2. $ctfile='/home/phppgm/logfiles/ctr.txt';3. $FILEH = fopen($ctfile, 'r+') or die ("Cannot open $ctfile");4. flock($FILEH, LOCK_EX) or die ("Cannot lock file $outf");5. $ctr = fgets($FILEH, 4096) or die ("Cannot gets $ctfile");6. $ctr = rtrim($ctr, '\n');7. if (is_numeric($ctr)){8. $count= $ctr + 1;9. rewind ($FILEH);10. $ret= fputs($FILEH, $count);11. print ("$count");12. } else {13. print "Error: ctr=$ctr <=not numeric value";14. }15. fclose ($FILEH);16. ?>

Page 27: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-27

The Output ...

The previous code can be executed at http://webwizard.aw.com/~phppgm/C6/drivecounter.html

Page 28: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-28

Another Full Script Example

Consider another example that implements an on-line survey: Asks end-user to select favorite tool

<input type="radio" name="tool" value="hammer" checked> Hammer<input type="radio" name="tool" value="wrench"> Wrench<input type="radio" name="tool" value="sdriver"> Screwdriver

<input type="radio" name="tool" value="fryingpan"> Frying Pan

Use survey file /home/phppgm/data/survey1.txt. 0:0:0:0 initial value

Page 29: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-29

A Full Script Example: Accessing the counter

Can place into this file and access it as:

<?php include 'counter.php' ?>

For example: <html><head><title>Harry's Place </title></head><body><font size=5 color=blue>Happy Harry's Hardware Home</font>

<br>Hit Count:<?php include 'counter.php' ?>

</body></html>

Page 30: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-30

PHP Script

1. <html><head><title>Happy Harry's Hardware Survey </title>2. </head><body>3. <font size=5 color="blue">Survey Results</font>4. <?php5. $ctfile='/home/phppgm/data/survey1.txt';6. $SURVEY = fopen($ctfile, 'r+') or die("Cannot open $ctfile");7. flock($SURVEY, LOCK_EX) or die ("Cannot lock file $outf");8. $inline = fread($SURVEY, 4096);9. list($hammer, $wrench, $sdriver, $fpan) = split(':', $inline);10. if ($tool == 'hammer'){11. $hammer = $hammer + 1;12. } elseif ($tool == 'sdriver') {13. $sdriver = $sdriver + 1;14. } elseif ($tool == 'wrench'){15. $wrench = $wrench + 1;16. } elseif ($tool == 'fryingpan'){17. $fpan = $fpan + 1;18. } else {19. die ('ERROR: Illegal call');20. }21. $ct=$hammer + $sdriver + $wrench + $fpan;22. print "<br>Hammer=$hammer Wrench=$wrench Screwdriver=$sdriver Frying Pan=$fpan Total votes=$ct";23. rewind($SURVEY);24. $ret= fputs($SURVEY, "$hammer:$wrench:$sdriver:$fpan");25. fclose ($SURVEY);?></body></html>

Page 31: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-31

PHP Script with REGISTER_GLOBALS Off

1. <html><head><title>Happy Harry's Hardware Survey </title>2. </head><body>3. <font size=5 color="blue">Survey Results</font>4. <?php $tool = $_POST[“tool”];5. $ctfile='/home/phppgm/data/survey1.txt';6. $SURVEY = fopen($ctfile, 'r+') or die("Cannot open $ctfile");7. flock($SURVEY, LOCK_EX) or die ("Cannot lock file $outf");8. $inline = fread($SURVEY, 4096);9. list($hammer, $wrench, $sdriver, $fpan) = split(':', $inline);10. if ($tool == 'hammer'){11. $hammer = $hammer + 1;12. } elseif ($tool == 'sdriver') {13. $sdriver = $sdriver + 1;14. } elseif ($tool == 'wrench'){15. $wrench = $wrench + 1;16. } elseif ($tool == 'fryingpan'){17. $fpan = $fpan + 1;18. } else {19. die ('ERROR: Illegal call');20. }21. $ct=$hammer + $sdriver + $wrench + $fpan;22. print "<br>Hammer=$hammer Wrench=$wrench Screwdriver=$sdriver Frying Pan=$fpan Total votes=$ct";23. rewind($SURVEY);24. $ret= fputs($SURVEY, "$hammer:$wrench:$sdriver:$fpan");25. fclose ($SURVEY);?></body></html>

Page 32: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-32

The Output ...

The previous code can be executed at http://webwizard.aw.com/~phppgm/C6/drivesurvey.html

Page 33: Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash

Copyright © 2003 Pearson Education, Inc. Slide 6b-33

Summary

Working with files enable scripts to store data for long periods of time. file() - read file into an array fopen() - open a file fgets() - read a line from file fputs() - write to a file. flock() - lock access to file.