Presentation is loading. Please wait.

Presentation is loading. Please wait.

ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data.

Similar presentations


Presentation on theme: "ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data."— Presentation transcript:

1 ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data

2 ITM 352 © Port,KazmanFile I/O - 2 Persistent Data Storage  Problem in mini-assignments:  Information gathered in forms and variables is only temporary– this info will disappear as soon as the page is reloaded or when the user navigates to another page.  Sometimes you need a way to keep data around between program executions (e.g. page loads)  Sometimes you need a way to share data between programs (e.g. between pages)  Three ways of more permanent (or persistent) data storage exist:  Files  Databases (we won't discuss these until ITM354)  Cookies/Sessions (we will discuss these shortly)

3 ITM 352 © Port,KazmanFile I/O - 3 Persistent Data Storage: Products  Let's say you have product data: Small Gumball; 0.02; Medium Gumball; 0.05; Large Gumball; 0.1;  This could be saved in a text file such as "product_data.dat"  How to use this data for our e-store?

4 ITM 352 © Port,KazmanFile I/O - 4 File Basics Files are controlled with "file pointers", which must be created before files are used. To open a file: $fp = fopen("name", ) This creates a handle or file pointer, called $fp The name can be in UNIX style (../../file.txt), Windows style (..\..\file.txt), a URL (http://www.hawii.edu/file.txt), or some other data stream (e.g. ftp). will be discussed next slide…

5 ITM 352 © Port,KazmanFile I/O - 5 File Opening Types  'r' - Open for reading only; place the file pointer at the beginning of the file.  'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.  'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

6 ITM 352 © Port,KazmanFile I/O - 6 More File Opening Types  'r+' - Open for reading and writing; place the file pointer at the beginning of the file.  'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.  'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.  These are generally less useful and more confusing, so I advise not using them.

7 ITM 352 © Port,KazmanFile I/O - 7 or die…  You can have PHP generate a specific error message if there is an error upon opening the file (permissions, disk space, etc.): $filename = "product_data.dat"; $h = fopen("$filename","r") or die("cannot open $filename"); Note the use of 'or', rather than '||'.

8 ITM 352 © Port,KazmanFile I/O - 8 Closing Files Always close a file when you're done with it– if you don't something can easily go wrong and corrupt your file. fclose($fp); (fclose returns TRUE on success or FALSE on failure. ) Why is this needed? Do Exercise #1

9 ITM 352 © Port,KazmanFile I/O - 9 File existence, Size of a file To check that a file exists, use: $filename = 'product_data.dat'; if( !file_exists($filename) ) echo "$filename does not exist!"; Often you will want the size of a file: echo "$filename is ". filesize($filename); Do Exercise #2

10 ITM 352 © Port,KazmanFile I/O - 10 Basic File I/O Example: Opening a File for Reading  To open a file or a URL we use fopen(). $filename = 'c:\file.txt'; $fp = fopen($filename, "r");

11 ITM 352 © Port,KazmanFile I/O - 11 Basic File I/O Example: Reading Info from a File  After we have opened the file, we will probably want to do something with it. To read the contents of a file into a variable we use fread(). $contents = fread($fp,filesize($filename)); fclose($fp);  Let us assume C:file.txt contains: 1: Hi there 2: Hello  So now $contents would be a string like: $contents = "1: Hi there\n 2: Hello\n"; Do Exercise #3

12 ITM 352 © Port,KazmanFile I/O - 12 Basic File I/O Example: Writing To a File  We can also write data into a file once we have opened it. To do this we use the fputs() function.  $filename = 'c:\file.txt'; $fp = fopen($filename, "a"); $string = "3: G'day\n"; $write = fputs($fp, $string); fclose($fp);  So now what will the file contain? 1: Hi there 2: Hello 3: G'day Do Exercise #4

13 ITM 352 © Port,KazmanFile I/O - 13 Basic File I/O Example: Reading Formatted Data  We can also read data from a file once we have opened it. To do this we use the fscanf() function. $filename = './file.txt'; $fp = fopen($filename, 'r'); while(fscanf($fp, '%d: %s\n', $number, $text)) { print "the text: $text is on line number: $number "; }; fclose($fp);  Prints the text: Hi is on line number: 1 the text: Hello is on line number: 2 the text: G'day is on line number: 3

14 ITM 352 © Port,KazmanFile I/O - 14 Warning: reading using fscanf can be tricky.  It's easier to read a line at a time, using fgets() or fgetss()... and then use strtok(), split(), or explode() to grab individual parts of the line. More on Reading Formatted Data

15 ITM 352 © Port,KazmanFile I/O - 15 <?php $fname = "test_file.txt"; // test_file.txt contains: $fp = fopen($fname, "r");// Dan Port;dport;portpass $size = filesize($fname);// Rick Kazman;kazman;kazpass // ITM352TA;itm352;password while($line_in = fgetss($fp, $size)) { echo "Got line: $line_in "; // $fields = explode (';', $line_in); $first = strtok($line_in, ";"); $second = strtok(";"); $third = strtok(","); echo "Tokens: $first / $second / $third "; } fclose($fp); ?> Reading Formatted Data: Example Code Do Exercise #5

16 ITM 352 © Port,KazmanFile I/O - 16 File Permissions To read from and write to files, certain permissions are necessary. Since the web interacts with our pages as the group (www), you may need to add group read, write and/or execute permissions. Permissions are changed with the folder properties in Windows, and the chmod command in UNIX

17 ITM 352 © Port,KazmanFile I/O - 17 PHP File Functions  PHP has many useful functions for manipulating files, such as:  fileread()  Reads a file into a string  file()  Reads a file into an array  unset()  Deletes a file  fileperms()  Provides statistics on a file  fscanf()  Reads a file in a particular format

18 ITM 352 © Port,KazmanFile I/O - 18 Why Use Files?  Often data needs to be stored for later use  Programs aren't always running (especially true of web applications which run only when a page is loaded) and data needs to be shared between different executions  Data needs to be shared between different programs  Keep data in a known location  Keeping the code separate from the data is a good programming practice.  Can make files work like an array, except they will persist.  Can do fancy stuff like binary encoding (for efficiency) or encryption (for security)

19 ITM 352 © Port,KazmanFile I/O - 19 Why NOT Use Files?  Typically users want simultaneous access to the data  Can't handle large amounts of data  No support for data analysis  No support for queries, reports, …  These ARE supported by relational DBs

20 ITM 352 © Port,KazmanFile I/O - 20 Things you can do with files...  User registration data  Products and services information  Real time inventory  Message board (the registration signup)  Shopping cart  Anything that requires persistent data.....

21 ITM 352 © Port,KazmanFile I/O - 21 Example: Project Registration Board (register_asst1.php: user registration input form) Please register your assignment #1 information. Be sure to verify that your description is different from any listed currently! Name: Describe your on-line store:

22 ITM 352 © Port,KazmanFile I/O - 22 ( messboard_ass1.php ) <?php $messFile = "./assignment1_regs.txt"; if(!empty($_POST['name'])) { echo "YOUR REGISTRATIONS FOR ASSIGNMENT #1 HAS BEEN RECEIVED (SEE END OF LIST) "; $fp = fopen($messFile, "a"); $data = 'IP address:'. $_SERVER["REMOTE_ADDR"]. ' Name: '. $_POST['name']. ' '. 'Description: '. $_POST['description'].' '. " -------------- -------------------------------- "; fwrite($fp, $data); fclose($fp); } Example: Writing Posted Data

23 ITM 352 © Port,KazmanFile I/O - 23 ( messboard_ass1.php cont ’ d ) if(file_exists($messFile)) { echo "CURRENT REGISTRATIONS FOR ASSIGNMENT #1 "; echo "----------------------------------------- "; $theFile = file($messFile); foreach($theFile as $value) { echo "$value\n"; echo " "; } } ?> Example: Reading Registrations

24 ITM 352 © Port,KazmanFile I/O - 24 Example: Persistent Arrays function arrayfile_to_array($filepath) { // This function reads the file at $filepath and returns an // array. It is assumed that the file being read is a // serialized array (created using array_to_arrayfile) $fsize = @filesize($filepath); if ($fsize > 0) { $fp = fopen($filepath, "r"); $encoded = fread($fp, $fsize); fclose($fp); return unserialize($encoded); } else echo "$filepath does not exist!"; }

25 ITM 352 © Port,KazmanFile I/O - 25 Example: Persistent Arrays (cont.) function array_to_arrayfile($theArray, $filepath) { // This function serializes an array in $theArray and saves it // in the file at $filepath. The file may then be converted // back into an array using the arrayfile_to_array() function) if($fp = fopen($filepath, "w+")) { $encoded = serialize($theArray); fwrite($fp, $encoded); fclose($fp); } else echo "Unable to write array to $filepath"; }


Download ppt "ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data."

Similar presentations


Ads by Google