php storing and retrieving data

18
1 PHP Storing and Retrieving Data

Upload: walker

Post on 18-Jan-2016

43 views

Category:

Documents


0 download

DESCRIPTION

PHP Storing and Retrieving Data. Reading from a File – a line at a time. string fgets (resource handle [, int length ]) Reads and returns one line from a file; moves file pointer to next line Reads until a newline, EOF, or until it has read length -1 bytes. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: PHP  Storing and Retrieving Data

1

PHP Storing and Retrieving Data

Page 2: PHP  Storing and Retrieving Data

string fgets(resource handle [, int length])Reads and returns one line from a file; moves file pointer to next lineReads until a newline, EOF, or until it has read length-1 bytes.

(length should be greater than the length in characters of the longest line in the file you are trying to read)

fopen() and fclose() have to be explicitly used

string fgetss(resource handle [, int length, string allowable_tags])Similar to fgets(), but strips out any HTML & PHP tags found in the

line read, except for those included in the allowable_tags stringExample: $line = fgetss($fp, 1024, "<p>,<b>");

2

Reading from a File – a line at a time

Page 3: PHP  Storing and Retrieving Data

array fgetcsv(resource handle [, int length) [, string delimiter [, string enclosure]]])Similar to fgets(), but breaks the line into fields using the delimiter

Returns an array containing the fields read or false on error.Example: $order = fgetcsv($fp, 100, "\t");

Knowing when to stop: feof(resource handle)feof() takes a file handle as a parameter feof() returns true if the file pointer is at the end of file, false

otherwise

3

Reading from a File – a line at a time

Page 4: PHP  Storing and Retrieving Data

View Ordershttp://cscdb.nku.edu/csc301/frank/PHP_IO_Examples/vie

worders.php

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

4

Page 5: PHP  Storing and Retrieving Data

@$fp = fopen("$DOCUMENT_ROOT/../../csc301_files/campana1.txt", "rb");

if(!$fp) { echo "<p><strong> No orders pending. Try again later." .

"</strong></p></body></html>"; exit;}

while (!feof($fp)) {$order = fgets($fp, 999);echo "<p>$order</p>";

}fclose($fp);

5

Reading from a File - Example

Page 6: PHP  Storing and Retrieving Data

int readfile(string filename [, ...])Opens the indicated file, echoes the content to the standard output (the

browser document) and closes the fileReturns the number of bytes read from the file or false on error

Other similar functions:file_get_contents(…) – identical to readfile(), except that it

returns the file content as a string instead of outputting it to the browserfile(…) – identical to readfile(), except that it returns the lines in

the file in an array, each line in a separate array elementbool fpassthru(resource handle) – accepts the file pointer

to an opened file, displays the file content to the standard output and closes the file; returns true for a successful read operation, false otherwise

6

Reading from a File – the whole file

Page 7: PHP  Storing and Retrieving Data

SF WeatherDisplays the content of the sfweather.txt text file, that

contains an “imaginary” weather forecast for San Francisco

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

7

Page 8: PHP  Storing and Retrieving Data

readfile("$DOCUMENT_ROOT/../../csc301_files/sfweather.txt");

// OR

$SFWeather = file_get_contents(

"$DOCUMENT_ROOT/../../csc301_files/sfweather.txt");echo $SFWeather;

8

Reading from a File - Example

Page 9: PHP  Storing and Retrieving Data

Reading a character at a timestring fgetc(resource handle) – reads and returns the next

character in the file (including EOF character)

while (!feof($fp)) {$char = fgetc($fp);if(!feof($fp)) // if the last read character is not EOF echo ($char=="\n" ? "<br />" : $char); // replaces \n with

<br />}

Reading an arbitrary length:string fread(resource handle, int length) – reads length bytes from the file and advances the file pointer

9

Reading from a File

Page 10: PHP  Storing and Retrieving Data

Locking Files

Uncontrolled concurrent access to a file can lead to unexpected results.

To prevent multiple users from modifying a file simultaneously use the flock() function:

bool flock(resource handle, int operation)

Function should be called after the file is opened, but before any data is read from / written to the file.

Function returns true if the lock was successfully acquired; false otherwise.

10

Page 11: PHP  Storing and Retrieving Data

Locking FilesPossible values for operation:

LOCK_EX = writing lock this operation is exclusive, the file cannot be shared with other writers or

readersLOCK_SH = reading lock

the file can be shared with other readersLOCK_UN = the existing lock is released

use it before closing the file however, the lock is released also by fclose(), which is also called

automatically when the script finishes.LOCK_NB = prevents the script from waiting to acquire a lock, if a

conflicting lock already exists on the file → does not work on Windows combine with LOCK_EX or LOCK_SH example: flock($fp, LOCK_EX & LOCK_NB);

11

Page 12: PHP  Storing and Retrieving Data

Locking Files

Note: the PHP locking mechanism is advisory on UNIX:PHP does not actually shut out other programs from accessing the file

PHP only prevents PHP scripts that use flock() from accessing a file that was locked by another PHP script using flock() too.

For the PHP file locking to be effective, it’s up to the programmer to ensure that:– any scripts that open a file use the flock() function and – no other programs access that file concurrently with the PHP scripts.

Note: the PHP locking mechanism is mandatory on Windows = the files are locked by the operating system; demo: lock_1.php vs notepad 12

Page 13: PHP  Storing and Retrieving Data

Obtaining File Information

13

Important pieces of information you need to obtain about files:

Whether the scripts have the necessary permissions to work with a file:

bool is_readable(string filename)

bool is_writeable(string filename)

Return true or false.

Use them to check permissions before attempting to read / write.

if (is_writable($WeatherFile)) { file_put_contents($WeatherFile, $DailyForecast); echo “<p>Forecast info saved to $WeatherFile file.</p>”;}else // ... Do not attempt to write!

Page 14: PHP  Storing and Retrieving Data

Obtaining File Information

14

Important pieces of information you need to obtain about files:Whether a file exists or not:bool file_exists(string filename)Returns true or false.

Determining the size of a file:int filesize(string filename)Returns the file size in bytes.Can be used in conjunction with fread() to read a whole file at a time.

where string nl2br(string s) function converts the \n characters in its string argument to HTML line breaks <br />

Page 15: PHP  Storing and Retrieving Data

15

Other Useful File FunctionsDelete a file

bool unlink(string filename)Pass the name of a file to the unlink() function

The function returns a value of true if successful or false if not ( → typically because the file doesn’t exist or permissions on the file are insufficient)

Page 16: PHP  Storing and Retrieving Data

16

Other Useful File FunctionsTo “navigate” inside a file = manipulate / discover the position of the

file pointer inside the file:

bool rewind(resource handle) → resets the file pointer to the beginning of the file

int ftell(resource handle) → returns the pointer position from the beginning of the file in bytes

int fseek(resource handle, int offset [, int whence]) → whence can be: SEEK_SET (beginning of file), SEEK_CUR (current position), SEEK_END (end of file)→ function sets file pointer at point indicated by whence + offset→ returns 1 on success, 0 otherwise

These functions are useful for processing files with fixed-length records.

Page 17: PHP  Storing and Retrieving Data

Other types of interaction with the server file system

Upload filesUsing directory and file functions to:

Read from directoriesGet info about current directoryCreate / delete directoriesGet more file infoChange file propertiesCreate / delete / move files

17

Page 18: PHP  Storing and Retrieving Data

Files vs Database Management Systems

Files – problems:Working with large files can be very slow;Searching for a particular record or group of records is slow; Insert/delete operations in the middle of the file are problematic:

read whole file into memory, make the change, write file back;Concurrent access is problematic, locking granularity is the file;Enforcing a data access policy can only rely on the file

permissions mechanism.

RDBMSs solve all these problems…

18