Presentation is loading. Please wait.

Presentation is loading. Please wait.

Storing and Retrieving Data

Similar presentations


Presentation on theme: "Storing and Retrieving Data"— Presentation transcript:

1 Storing and Retrieving Data
PHP Storing and Retrieving Data

2 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: 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.

3 Files Objectives – learn how to: Open and close files
Write data to files Read data from files Lock files Delete files Obtain file information

4 Accessing Files Reading data from a file and writing data to a file require 3 steps: Open the file Read data from or write data to the file Close the file

5 Opening a File To 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. 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

6 Opening a File Example – 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

7 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.

8 Opening a File – Access Types
Mode arguments of the fopen() function: append read write and file is not opened cautious write 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

9 Opening a File – Access Types
$fp = fopen(“orders.txt”, “r+”); Location of the file pointer when the fopen() function uses a mode argument of “r+”

10 Opening a File – Access Types
$fp = fopen(“orders.txt”, “a+”); Location of the file pointer when the fopen() function uses a mode argument of “a+”

11 Addressing Problems Opening Files
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 See later how to verify whether you have security access to files to which you want to write or read data.

12 Addressing Problems Opening Files
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 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 }

13 Closing a File 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.

14 Writing to a File 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 filename The 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

15 Writing to a File 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

16 Bob's Auto Parts Form

17 Writing to a File - Example
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";

18 Writing to a File - Example
@ $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) else echo "<p>Your order could not be processed ...</p>";


Download ppt "Storing and Retrieving Data"

Similar presentations


Ads by Google