200 likes | 249 Views
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.
E N D
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. (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 string • Example: $line = fgetss($fp, 1024, "<p>,<b>");
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
View Orders • http://cscdb.nku.edu/csc301/frank/PHP_IO_Examples/vieworders.php • http://www.nku.edu/~frank/csc301/Examples/PHP_IO_Examples/vieworders_php.pdf
Reading from a File - Example @$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);
Reading from a File – the whole file • int readfile(string filename [, ...]) • Opens the indicated file, echoes the content to the standard output (the browser document) and closes the file • Returns 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 browser • file(…) – identical to readfile(), except that it returns the lines in the file in an array, each line in a separate array element • boolfpassthru(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
SF Weather • Displays 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
Reading from a File - Example readfile("$DOCUMENT_ROOT/../../csc301_files/sfweather.txt"); // OR $SFWeather = file_get_contents( "$DOCUMENT_ROOT/../../csc301_files/sfweather.txt"); echo $SFWeather;
Reading from a File • Reading a character at a time • string 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
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.
Locking Files • Possible values for operation: • LOCK_EX = writing lock • this operation is exclusive, the file cannot be shared with other writers or readers • LOCK_SH = reading lock • the file can be shared with other readers • LOCK_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);
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
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 “<p>Forecast info saved to $WeatherFile file.</p>”; } 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 <br />
Other Useful File Functions • Delete 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)
Other Useful File Functions • To “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.
Other types of interaction with the server file system • Upload files • Using directory and file functions to: • Read from directories • Get info about current directory • Create / delete directories • Get more file info • Change file properties • Create / delete / move files
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…