home—lects—exams—hws
D2L—breeze (snow day)
lect09c-ch11-files
files and directories
chapter 11
Originally based on
PHP Visual Quickstart Guide by Larry Ullman,
and notes therefrom by by Jack Davis (jcdavis@radford.edu).
There is a tower of increasingly sophisticated ways to share state between pages:
-
No sharing -- just individual pages.
-
includeing files -- can share constants, common code, headers.
-
Forms,
via GET (info embedded in URLs; bookmarkable)
or POST (info in the HTTP request, but not displayed as part of the URL).
-
Cookies (stored by the client, auto-passed with each HTTP request.)
-
Sessions (info stored server-side; php program accesses the $_SESSION array.
-
files, read/written by php programs on the server
-
a database, read/written by php programs on the server
There are two primary ways of storing data with PHP; using files (and directories)
or databases. This chapter will discuss the former, and the next chapter will
introduce the latter. Although a database can be more powerful and secure
than a file-based system, it is surprising how much can be done by sending
and retrieving information from simple text documents on the server.
- File Permissions
The set up of the RU Apache/PHP web server is one where the php programs are run
as the owner.
So, the permissions only have to be set to 700.
However, data files still have
to be readable to others to be accessed by the php program the server is executing.
You should review the file permission standards for Unix and the RU set up.
- To use (read or write) from a file first it must be opened:
$fp = fopen(filename, mode);
The File Modes are:
- r to read only;
- r+ to read or writing
- w write only;
create the file if it doesn't exist, overwrite if it does
- w+ read or write; overwrite if exists
- a, a+ write (or read-write),
appending the new data to the end of any existing data
- x x+ write (or, read-write) a new file;
create warning if the file does exist
Reading Files
The fgets function
gets a string1 (line) from a file.
The newline character is included in the result
(though if the end-of-file was reached, there may not be a terminating newline).
(N.B. This is different from C's fgets!)
fgets is most often called from inside a while loop
that checks for end-of-file with feof:
$fp = fopen('myData.txt', 'r');
while (!feof($fp)) {
$string = fgets($fp, 1024);
// Read until end-of-line (or 1023 chars: imagine room for a \n) (or EOF)
}
fclose($fp);
|
- $array = fgetcsv($fp,length,delimiter);
In a file where the data is stored in a delimited format
(commonly using a comma, hence “CSV” -- “comma separated values”) you can
use the fgetcsv() function instead of fgets().
- The file function reads a file and returns
an array of strings — one entry for each line.
$allLines = file('.\lect09c-ch11-files-sayings.txt');
// $allLines[0] now contains the first line of the file.
|
Example: lect09c-ch11-files-read.php
- file_get_contents() works like file() function,
but stuffs all of the lines in the file into one string.
- Because some of these functions rely upon identifying the end of a line,
it's a good idea to enable PHP's auto_detect_line_endings setting as in:
ini_set('auto_detect_line_endings',1);
Writing to a file
- fwrite: e.g. fwrite($fp, 'data to be written\n')
Writes the new data to the file in accordance with the selected mode
(appending to previous fwrites since opening).
Normally, each piece of data to be written on its own line, so each submission
should conclude with the appropriate line break for the operating system of the
computer running PHP.
For *nix (incl. RU, Mac OSX) that's \n;
for DOS/Windows
(and a
few others),
that's \r\n
(and for Mac OS 9-, it was just \r, sigh!).
fopen's mode can be suffixed with b for raw-binary,
which does no translation of newlines;
this is recommended for portability.
E.g. fopen('myFile.txt','rb').
While Windows does also offer
a t mode to translate \n to \r\n,
this makes your code highly platform-dependent.
Instead, try the
auto-detect-line-endings configuration (ini) option.
-
For robustness/portability:
set the file's stream_encoding (usually to 'utf-8'),
rather than rely on whatever the server's default happens to be.
- Example: lect09c-ch11-files-rw.php
- Locking Files
Realize that many users execute server side programs simultaneously,
so we sometimes need
to be sure a particular instance of the program is able to
complete its write before another
process start the write.
We can lock a file, to have the system ensure two programs
don't open the file at once:
flock($fp,LOCK_EX);
fwrite($fp, 'data to be written...\n');
flock($fp,LOCK_UN);
|
- File Uploads
The helpful html form-input:
<input name="MyUploadedFile" type="file" />
When the enclosing form is submitted,
we don't get anything in $_POST['MyUploadedFile'];
instead php uploads the file
using both an invented temporary name
(to avoid clashes),
plus remembering the file's original name.
Within our PHP, use the superglobal $_FILES['MyUploadedFile'],
which contains an entire associative array of information about the file:
Example: lect09c-ch11-files-upload.php
Note that this script uses
move_uploaded_file, to move (rename) the file.
This function verifies that the file really is one that was previously uploaded.
(Which in turn means, you can only call this once on a file,
since after it's been moved it's considered a regular, non-uploaded file.)
1
As opposed to fgetc to get a single character.
↩
home—lects—exams—hws
D2L—breeze (snow day)