Internet Programming Work with Files in PHP

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 7-1 The Web Wizards Guide to PHP by David Lash.
Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizards Guide to PHP by David Lash.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizards Guide to PHP by David Lash.
Copyright © 2003 Pearson Education, Inc. Slide 1-1 The Web Wizards Guide to PHP by David A. Lash.
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
More on PHP Coding Lab no. 6 Advance Database Management System.
Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizard’s Guide to PHP by David Lash.
1 Controlling Script Flow! David Lash Chapter 3 Conditional Statements.
Introduction to PERL Part 4 (1) Working with Files (2)CGI Security.
There is a certain way that an HTML file should be set up. The HTML section declares a beginning and an ending. Within the HTML, there should be a HEAD.
Reading and Writing Data Files Why do you need reading and writing data files in your CGI programming? Web server does not have permission to create file.
Slide 6a-1 CHAPTER 6 Matching Patterns: Using Regular expressions to match patterns.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
PHP : Hypertext Preprocessor
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
Slide 8-1 CHAPTER 8 Using Databases with PHP Scripts: Using MySQL Database with PHP.
Copyright © 2003 Pearson Education, Inc. Slide 1-1 Web Design & Development PHP.
Networking Overview Your OUNet ID ("4 plus 4") OUNet Password Changing Your OUNet Password Your Official OU Forwarding Your Mail Getting Help Overview.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 12.
Web Design and Development for E-Business By Jensen J. Zhao Copyright 2003 Prentice Hall, Inc. Web Design and Development for E-Business Jensen J. Zhao.
1Copyright © 2011 Pearson Education, Inc. Publishing as Prentice Hall. Exploring Microsoft Access 2010 by Robert Grauer, Keith Mast, Mary Anne Poatsy Chapter.
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 11.
Week Three CIT 354 Internet II. 2 Objectives Displaying Dynamic Content Sending Using Your File System Common Programming Errors Summary Quiz,
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
 2008 Pearson Education, Inc. All rights reserved Introduction to XHTML.
Slide 7-1 CHAPTER 7 Managing Multiple-Form Applications: Writing scripts with multiple screens.
1 Chapter 4 – Breaking It Up: Functions spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Slide 3-1 CHAPTER 3 Conditional Statements Objectives To learn to use conditional test statements to compare numerical and string data values To learn.
Diagnostic Pathfinder for Instructors. Diagnostic Pathfinder Local File vs. Database Normal operations Expert operations Admin operations.
Creating PHPs to Insert, Update, and Delete Data CS 320.
XHTML & Forms. PHP and the WWW PHP and HTML forms – Forms are the main way users can interact with your PHP scrip Typical usage of the form tag in HTML.
1 Module 3 Conditional Statements. Objectives  Conditional test statements to compare numerical and string data values  Looping statements to repeat.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
Storing and Retrieving Data
5 1 Data Files CGI/Perl Programming By Diane Zak.
Copyright © 2003 Pearson Education, Inc. Slide 7-1 The Web Wizard’s Guide to PHP by David Lash.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Web Page Design Forms! Website Design. Objectives What forms can do The Attributes of the form tag Using Textboxes Textareas Checkboxes Radio buttons.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
ASP (COMPONENTS) Active Server Pages (cont..) 1. global.asa file The Global.asa file is an optional file that can contain declarations of objects, variables,
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
Copyright © 2003 Pearson Education, Inc. Slide 3-1 The Web Wizard’s Guide to PHP by David A. Lash.
Copyright © 2003 Pearson Education, Inc. Slide 7-1 The Web Wizard’s Guide to PHP by David Lash.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
The Web Wizard’s Guide to PHP by David Lash
Chapter 6 Persistence-Saving and Retrieving Data
Receiving form Variables
GO! with Microsoft Office 2016
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
1 CHAPTER 10 ADVANCED PHP.
GO! with Microsoft Access 2016
* Lecture # 7 Instructor: Rida Noor Department of Computer Science
Introduction to Programming the WWW I
HTML.
Cookies BIS1523 – Lecture 23.
HTML Forms and User Input
<?php require("header.htm"); ?>
In Class Programming BIS1523 – Lecture 11.
The Web Wizard’s Guide to PHP
File I/O in PHP Persistent Data.
PHP: Hypertext Preprocessor
Lecture 6: Processing Forms with PHP
PHP-II.
ITS 180: Database Management Systems
The Web Wizard’s Guide to PHP by David A. Lash
Presentation transcript:

Internet Programming Work with Files in PHP Copyright © 2003 Pearson Education, Inc.

Using files on the Web Server From PHP Scripts CHAPTER 6 Working with Files: Using files on the Web Server From PHP Scripts 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 Copyright © 2003 Pearson Education, Inc.

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 Copyright © 2003 Pearson Education, Inc.

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 assigned 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 Copyright © 2003 Pearson Education, Inc.

Reading A file the easy way. 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: Using file() works well but does consume memory Can slow scripts down for large files Copyright © 2003 Pearson Education, Inc.

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 Copyright © 2003 Pearson Education, Inc.

Using file open mods Copyright © 2003 Pearson Education, Inc.

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. Copyright © 2003 Pearson Education, Inc.

Using fgets() to read Open you open a file for reading use fgets() to read it: Copyright © 2003 Pearson Education, Inc.

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.50 AC1001:Wrenches:5:5.00 AC1002:Handsaws:10:10.00 AC1003:Screwdrivers:222:3.00 Copyright © 2003 Pearson Education, Inc.

PHP Script 1. <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> Copyright © 2003 Pearson Education, Inc.

The Output ... Copyright © 2003 Pearson Education, Inc.

Writing to Files You can use the fputs() function The above outputs: “My script was here” into the file that $OFILE points to Copyright © 2003 Pearson Education, Inc.

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); Copyright © 2003 Pearson Education, Inc.

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> Copyright © 2003 Pearson Education, Inc.

PHP Script 1. <html> <head><title>Log Comments</title></head> <body> 2.<?php 3. $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:”.$_POST[‘comments’].”\n"; 7. print "Just Logged: <br> $msg"; 8. fputs($OUTF, $msg); 9. fclose($OUTF); 10.?> 11. </body></html> Copyright © 2003 Pearson Education, Inc.

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, it may corrupt the file A corrupted file is a useless unintelligible mixture of data. Copyright © 2003 Pearson Education, Inc.

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 Copyright © 2003 Pearson Education, Inc.

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 Copyright © 2003 Pearson Education, Inc.

Reading and Writing Files When reading and writing from same file you 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'); Copyright © 2003 Pearson Education, Inc.

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: A B C After script segment runs, the file will contain: Z Copyright © 2003 Pearson Education, Inc.

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' ?> Copyright © 2003 Pearson Education, Inc.

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> Copyright © 2003 Pearson Education, Inc.

PHP Script 1. <?php 2. $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. ?> Copyright © 2003 Pearson Education, Inc.

The Output ... Copyright © 2003 Pearson Education, Inc.

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 Copyright © 2003 Pearson Education, Inc.

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. <?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> Copyright © 2003 Pearson Education, Inc.

The Output ... Copyright © 2003 Pearson Education, Inc.

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. Copyright © 2003 Pearson Education, Inc.