18
1 PHP Storing and Retrieving Data

PHP Storing and Retrieving Data

Embed Size (px)

DESCRIPTION

PHP Storing and Retrieving Data. Files. Data can be stored in two basic ways: Flat files (meaning text files) Databases → for larger amounts of information PHP programs can read and write files on the server . Some uses: - PowerPoint PPT Presentation

Citation preview

Page 1: PHP  Storing and Retrieving Data

1

PHP Storing and Retrieving Data

Page 2: PHP  Storing and Retrieving Data

FilesData can be stored in two basic ways:

Flat files (meaning text files)Databases → for larger amounts of information

PHP programs can read and write files on the server.

Some uses:Web site data; example: store questions and answers for the

quiz in a file, read from file to generate the quiz;Save user input; example: save customer orders to a file;Maintain password data in a file;Maintain hit counter in a file.

2

Page 3: PHP  Storing and Retrieving Data

Files

Objectives – learn how to:Open and close filesWrite data to filesRead data from filesLock filesDelete filesObtain file information

3

Page 4: PHP  Storing and Retrieving Data

Accessing Files

Reading data from a file and writing data to a file require 3 steps:Open the fileRead data from or write data to the fileClose the file

4

Page 5: PHP  Storing and Retrieving Data

Opening a FileTo open a file, use the fopen() function Syntax:

$file_handle = fopen(“path/file_name”, “mode”);

Two other optional parameters can be used with fopen() – not discussed here. 5

• if fopen() succeeds, a resource which is a handle or pointer to the file is returned and should be stored for using when reading from/ writing to the file

• relative path in the server’s file system – indicate relative to web doc root or current directory;

• absolute path in the server’s file system – not recommended, loca-tion of the used file might change;

• if no path is indicated, the file is looked for /created in the same directory as the script itself

• “file mode” → a string that specifies what you want to do with the file: read, write, read & write, append or overwrite

Page 6: PHP  Storing and Retrieving Data

Opening a FileExample – open Bob’s order file to write a customer order:

$fp = fopen($_SERVER[‘DOCUMENT_ROOT’].

“../../csc301_files/campana1.txt”, “w”);Notes:

the PHP built-in variable $_SERVER[‘DOCUMENT_ROOT’] points at the base of the document tree on the web server; this is ‘D:/www’ on cscdb.nku.edu.

as with the form variables, there are 3 ways to access the predefined server variables: $_SERVER[‘DOCUMENT_ROOT’] (preferred) , $DOCUMENT_ROOT, $HTTP_SERVER_VARS[‘DOCUMENT_ROOT’].

the relative path in the example leads to a file outside the web document tree, for security reasons: the file should not be web accessible otherwise than through the interface (=php scripts) we provide; demo

6

Page 7: PHP  Storing and Retrieving Data

Opening a File – Access Types

Describe what you want to do with the file.Determine:

if/how other scripts can manipulate the opened file, the position in the file from where you start to operate on the file

content.

Are used to check if the script has the right permissions to use the file as requested;

Note that the PHP scripts run under a specific OS user (on Windows, LocalSystem or another user the administrator sets for Apache), that has specific permissions set for using files.

7

Page 8: PHP  Storing and Retrieving Data

Opening a File – Access TypesMode arguments of the fopen() function:

8

append

read

write

cautious write

and file is not opened

and file is not opened

fopen() with a, a+, w, w+ tries to create inexistent files, but not directories in the path

Text and binary flags (t ,b) can be combined with mode arguments; b recommended

Page 9: PHP  Storing and Retrieving Data

$fp = fopen(“orders.txt”, “r+”);

Location of the file pointer when the fopen() function uses a mode argument of “r+”

9

Opening a File – Access Types

Page 10: PHP  Storing and Retrieving Data

$fp = fopen(“orders.txt”, “a+”);

Location of the file pointer when the fopen() function uses a mode argument of “a+”

10

Opening a File – Access Types

Page 11: PHP  Storing and Retrieving Data

If the user under which the script runs usually: a web server user such as IUSR for Internet Information Server,

LocalSystem that runs by default the Apache service on Win etc.

doesn’t have permission to access the file you are trying to open errors

11

Addressing Problems Opening Files

See later how to verify whether you have security access to files to which you want to write or read data.

Page 12: PHP  Storing and Retrieving Data

How to deal with an error generated by an attempt to open a file:Suppress PHP’s error message:

@ $fp = fopen($_SERVER[‘DOCUMENT_ROOT’]. “../../csc301_files/campana1.txt”, “a+”);

The error suppression operator @ can be used in front of any expression (=anything that has/generates a value).

@ will suppress any errors resulting from the fopen() function call.

Give your own user-friendly error-message:

if (!$fp) { // fopen() returns false if file cannot be opened! echo “<p><strong>Your order could not be processed at this time. Please try again later. </strong></p></body></html>”;

exit; // as page ends here, close HTML tags to give reasonably valid HTML} 12

Addressing Problems Opening Files

Page 13: PHP  Storing and Retrieving Data

Use the fclose() function when finished working with a file to save space in memory (=> memory allocated for the file resource is freed):

fclose($fp);

fclose() function returns true if the file was successfully closed or false if it wasn’t.

Closing a file is much less likely to go wrong than opening a file no test.

13

Closing a File

Page 14: PHP  Storing and Retrieving Data

PHP supports two basic functions for writing data to text files: int file_put_contents(string filename, string data [, options]) This function writes the string contained in data (the second argument)

to the file named in filenameThe file doesn’t have to be explicitly opened and closed using fopen()

and fclose()!If the file doesn’t exist, the function attempts to create it (not the

directories in the path however!)If the file exists:

Without a 3rd argument, its content is overwritten With FILE_APPEND as a 3rd argument, data is appended at the end of the file

This function returns the number of bytes written to the file, 0 if no content is written

14

Writing to a File

Page 15: PHP  Storing and Retrieving Data

PHP supports two basic functions for writing data to text files:int fwrite(resource handle, string data [, int length]) This function writes the string contained in the string data to the file

pointed to by handle; The 3rd optional argument is the maximum number of bytes to write →

use strlen(data) to indicate that the whole data string is to be written

fopen() and fclose() have to be explicitly used with fwrite() The function returns the number of bytes written to the file, 0 if no

content is written

15

Writing to a File

Page 16: PHP  Storing and Retrieving Data

Bob's Auto Parts Formhttp://cscdb.nku.edu/csc301/frank/PHP_IO_Examples/ord

erform_4.html

http://www.nku.edu/~frank/csc301/Examples/PHP_IO_Examples/orderform_4_php.pdf

16

Page 17: PHP  Storing and Retrieving Data

A record = one separate line of text is written for each order;

The record separator is \r\n (on Win);

Fields will be separated by \t (the separator character should be something that will certainly not occur in the input!);

The record and field separators allow to subsequently read the data from the file and split it back into separate variables.

A record:$outputString = $date . "\t" . $tireqty . " tires\t" . $oilqty .

" oil\t" . $sparkqty . " spark plugs\t$" .

$totalamount . "\t" . $address . "\r\n";

17

Writing to a File - Example

Page 18: PHP  Storing and Retrieving Data

@ $fp = fopen("$DOCUMENT_ROOT/../../csc301_files/campana1.txt","ab");if (!$fp) {

echo "<p><strong>Your order could not be processed ... </strong></p></body></html>"; exit;

}flock($fp, LOCK_EX);fwrite($fp, $outputString, strlen($outputString));flock($fp, LOCK_UN);fclose($fp);echo "<p>Order written.</p>";--------------------------------------------------------------------if (file_put_contents(“orders.txt”, $outputString, FILE_APPEND) > 0)

echo "<p>Order written.</p>";else echo "<p>Your order could not be processed ...</p>";

18

Writing to a File - Example