1 / 25

Persistent Data File I/O in PHP

Learn about persistent data storage in PHP using files. Explore how to open, read, and write data to files, as well as check file existence and size.

leonetti
Download Presentation

Persistent Data File I/O in PHP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Persistent Data File I/O in PHP

  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. 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. File Basics Files are controlled with "file pointers", which must be created before files are used. To open a file: $fp = fopen("name", <open type>) 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). <open type>will be discussed next slide…

  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. 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. 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. 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. 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. 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. 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. 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. 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<br>"; }; 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. More on Reading Formatted Data Warning: reading using fscanf can be tricky. • It's easier to read a line at a time, using fgets() orfgetss() ... and then use strtok(), split(), or explode() to grab individual parts of the line.

  15. Reading Formatted Data: Example Code <?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<br>"; // $fields = explode (';', $line_in); $first = strtok($line_in, ";"); $second = strtok(";"); $third = strtok(","); echo "Tokens: $first / $second / $third<p>"; } fclose($fp); ?> Do Exercise #5

  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. 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. 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. 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. 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. Example: Project Registration Board (register_asst1.php: user registration input form) <html> <body> Please register your assignment #1 information. Be sure to verify that your description is different from any listed currently! <form action="messboard_ass1.php" method="post"> Name: <input type="text" name="name" /> <p></p> Describe your on-line store: <TEXTAREA name="description" rows="10" cols="80" wrap="PHYSICAL"></TEXTAREA> <input type="submit" value="Register"/> </form> </body> </html>

  22. Example: Writing Posted Data (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)<p></p>";$fp=fopen($messFile,"a");$data= 'IP address:'.$_SERVER["REMOTE_ADDR"].'<p>Name: '.$_POST['name'].'<p>'. 'Description: '.$_POST['description'].'<BR>'. "<p>---------------------------------------------- <p>";fwrite($fp,$data);fclose($fp); }

  23. Example: Reading Registrations (messboard_ass1.php cont’d) if(file_exists($messFile)) {echo"CURRENT REGISTRATIONS FOR ASSIGNMENT #1<p>";echo"-----------------------------------------<p>";$theFile=file($messFile);foreach($theFileas$value) {echo"$value\n";echo"<br>";} } ?>

  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. 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"; }

More Related