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

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

Embed Size (px)

Citation preview

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

ITM 352 © Port,Kazman File I/O - 1

File I/O in PHP

Persistent Data

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

ITM 352 © Port,Kazman File 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)

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

ITM 352 © Port,Kazman File 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?

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

ITM 352 © Port,Kazman File 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", <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…

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

ITM 352 © Port,Kazman File 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.

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

ITM 352 © Port,Kazman File 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.

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

ITM 352 © Port,Kazman File 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 '||'.

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

ITM 352 © Port,Kazman File 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

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

ITM 352 © Port,Kazman File 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

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

ITM 352 © Port,Kazman File I/O - 10

Basic File I/O Example:

Opening a File for ReadingTo open a file or a URL we use fopen().

$filename = 'c:\file.txt';

$fp = fopen($filename, "r");

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

ITM 352 © Port,Kazman File 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

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

ITM 352 © Port,Kazman File 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: Hello3: G'day

Do Exercise #4

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

ITM 352 © Port,Kazman File 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<br>";};fclose($fp);

Printsthe text: Hi is on line number: 1the text: Hello is on line number: 2the text: G'day is on line number: 3

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

ITM 352 © Port,Kazman File 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

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

ITM 352 © Port,Kazman File 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<br>";

// $fields = explode (';', $line_in);

$first = strtok($line_in, ";");

$second = strtok(";");

$third = strtok(",");

echo "Tokens: $first / $second / $third<p>";

}

fclose($fp);

?>

Reading Formatted Data: Example Code

Do Exercise #5

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

ITM 352 © Port,Kazman File 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

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

ITM 352 © Port,Kazman File 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

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

ITM 352 © Port,Kazman File 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)

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

ITM 352 © Port,Kazman File I/O - 19

Why NOT Use Files?

Typically users want simultaneous access to the data

Can't handle large amounts of dataNo support for data analysisNo support for queries, reports, …

These ARE supported by relational DBs

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

ITM 352 © Port,Kazman File I/O - 20

Things you can do with files...User registration dataProducts and services informationReal time inventoryMessage board (the registration signup)Shopping cart

Anything that requires persistent data.....

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

ITM 352 © Port,Kazman File I/O - 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>

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

ITM 352 © Port,Kazman File 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)<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);

}

Example: Writing Posted Data

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

ITM 352 © Port,Kazman File I/O - 23

(messboard_ass1.php cont’d)

if(file_exists($messFile)) {

echo "CURRENT REGISTRATIONS FOR ASSIGNMENT #1<p>"; echo "-----------------------------------------<p>"; $theFile = file($messFile); foreach($theFile as $value) { echo "$value\n"; echo "<br>"; }

} ?>

Example: Reading Registrations

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

ITM 352 © Port,Kazman File I/O - 24

Example: Persistent Arraysfunction 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!";}

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

ITM 352 © Port,Kazman File 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";

}