1 PHP Storing and Retrieving Data. string fgets(resource handle [, int length]) Reads and returns one line from a file; moves file pointer to next line.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

PHP I.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
NCHU System & Network Lab Lab 15 Record Locking. NCHU System & Network Lab Record Locking (1/4) What happens when two process attempt to edit the same.
More on PHP Coding Lab no. 6 Advance Database Management System.
Chapter 4 Working with Files and Directories PHP Programming.
More on Functions PHP mod 4 B. Simple Mail Transfer Protocol (SMTP) mail($to, $subject, $msg, $mailheaders); m08/8-1simple_form.html m08/8-1send_simpleform.php.
FILES Files types and operations. Files Files are used to store data Data can be Text (ASCII only: 0  127) Binary (Full range: 0  256) Each file resides.
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 6 Working with Files and Directories PHP Programming with MySQL.
Guide To UNIX Using Linux Third Edition
IS 1181 IS 118 Introduction to Development Tools Week 2.
FILE UPLOADS CHAPTER 11. THE BASIC PROCESS 1.The HTML form displays the control to locate and upload a file 2.Upon form submission, the server first stores.
PHP Programming. Topics Background and History of PHP Installation Comments in PHP Variables Conditions Loops Functions File Handling Database Handling.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
PHP Programming with MySQL Slide 6-1 CHAPTER 6 Working with Files and Directories.
18. PHP File Operations Opening a File
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
Fall 2004CSI University of Ottawa Introduction to PHP Basic principles and syntax.
1 Chapter 7 – Object-Oriented Programming and File Handling spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Storing and Retrieving Data
Introduction to File Processing with PHP - Part 2 Indexed Files.
Outline Overview Opening a file How to create a file ? Closing a File Check End-of-file Reading a File Line by Line Reading a File Character by Character.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
PHP Programming.
PHP 4 Files, Functions. Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the.
Chapter 5 Working with Files and Directories PHP Programming with MySQL 2 nd Edition.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Files Tutor: You will need ….
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
 A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
File Systems - Part I CS Introduction to Operating Systems.
Files A collection of related data treated as a unit. Two types Text
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Flock in PHP By Chao Liang. Basic Flock Concept What is flock? Abbreviation for file locking Why flock? Data consistency. Prevent file corruption. Different.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
FILE I/O: Low-level 1. The Big Picture 2 Low-Level, cont. Some files are mixed format that are not readable by high- level functions such as xlsread()
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
TMF1414 Introduction to Programming
CS111 Computer Programming
Topics Introduction to File Input and Output
<?php require("header.htm"); ?>
Text and Binary File Processing
File Input and Output.
Fundamental of Programming (C)
Lecture 6: Processing Forms with PHP
Topics Introduction to File Input and Output
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

1 PHP Storing and Retrieving Data

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, ", "); 2 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 3 Reading from a File – a line at a time

View Orders worders.php worders.php amples/vieworders_php.pdf amples/vieworders_php.pdf 4

@$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); 5 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 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 bool 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

SF Weather Displays the content of the sfweather.txt text file, that contains an “imaginary” weather forecast for San Francisco amples/sfweather_php.pdf amples/sfweather_php.pdf 7

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

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" ? " " : $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 9 Reading from a File

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

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); 11

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

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 “ Forecast info saved to $WeatherFile file. ”; } else //... Do not attempt to write!

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

15 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)

16 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 17

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