php storing and retrieving data

Click here to load reader

Post on 18-Jan-2016

30 views

Category:

Documents

0 download

Embed Size (px)

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

  • *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, ","); *Reading from a File a line at a time

  • 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*Reading from a File a line at a time

  • View Ordershttp://cscdb.nku.edu/csc301/frank/PHP_IO_Examples/vieworders.php

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

    *

  • @$fp = fopen("$DOCUMENT_ROOT/../../csc301_files/campana1.txt", "rb");if(!$fp) { echo " No orders pending. Try again later." . ""; exit;}while (!feof($fp)) {$order = fgets($fp, 999);echo "$order";}fclose($fp);*Reading from a File - Example

  • 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 errorOther 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*Reading from a File the whole file

  • 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

    *

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

    // OR

    $SFWeather = file_get_contents( "$DOCUMENT_ROOT/../../csc301_files/sfweather.txt");echo $SFWeather; *Reading from a File - Example

  • 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" ? "" : $char); // replaces \n with }Reading an arbitrary length:string fread(resource handle, int length) reads length bytes from the file and advances the file pointer*Reading from a File

  • Locking FilesUncontrolled 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.*

  • Locking FilesPossible values for operation:LOCK_EX = writing lockthis 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 filehowever, 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 Windowscombine with LOCK_EX or LOCK_SHexample: flock($fp, LOCK_EX & LOCK_NB);*

  • Locking FilesNote: the PHP locking mechanism is advisory on UNIX:PHP does not actually shut out other programs from accessing the filePHP 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, its 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*

  • Obtaining File Information*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 Forecast info saved to $WeatherFile file.;}else // ... Do not attempt to write!

  • Obtaining File Information*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

  • *Other Useful File FunctionsDelete a filebool unlink(string filename)Pass the name of a file to the unlink() functionThe function returns a value of true if successful or false if not ( typically because the file doesnt exist or permissions on the file are insufficient)

  • *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 fileint 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 otherwiseThese functions are useful for processing files with fixed-length records.

  • Other types of interaction with the server file systemUpload filesUsing directory and file functions to:Read from directoriesGet info about current directoryCreate / delete directoriesGet more file infoChange file propertiesCreate / delete / move files*

  • Files vs Database Management SystemsFiles 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

    *

    ********

View more