Unit-III
Working with Files and Directories
Understanding Files and
Directories
A
file is nothing more than an ordered sequence of bytes stored on a hard
disk or other storage media.
A
directory is a special type of file that holds the names of the files
and directories inside the folder(sometimes denoted as subdirectories or
subfolders ) and pointers to their storage areas on the media.
UNIX
- based systems such as Linux use slashes :
/home/matt/data/data.txt
Windows
uses backslashes:
C:\MyDocs\data\data.txt
In
PHP you need to use two backslashes in a row, because PHP interprets a
backslash as escaping the following character:
“C:\\MyDocs\\data\\data.txt”
Getting Information on Files :
PHP provides some
functions
file_exists() to discover
whether a file exists before attempting to open it:
file_exists(
“/home/chris/myfile.txt” )
file_exists() returns true if
the file at the specified path exists, or false otherwise.
filesize() function to
determine the size of a file on the hard disk.
filesize(
“/home/chris/myfile.txt” ) //
This
returns the size of the specified file in bytes, or false upon error.
Time
- Related Properties
PHP
provides three time - related file functions:
fileatime()
—
Returns the time at which the file was last accessed as a UNIX timestamp.A file
is considered accessed if its contents are read
filectime()
—
Returns the time at which the file was last changed as a UNIX timestamp.A file
is considered changed if it is created or written, or when its permissions have
been changed
filemtime()
— Returns
the time at which the file was last modified as a UNIX timestamp.The file is
considered modified if it is created or has its contents changed
Retrieving
a Filename from a Path
basename()
function taking a complete file path and returning just the filename. Basically, basename() retrieves the last whole string
after the rightmost slash. For example, the following code assigns index.html
to $filename :
$filename
= basename( “/home/james/docs/index.html” );
Opening and Closing Files
·
Usually,
to work with a file from within your PHP script, you first need to open the
file.
·
When
you open a file, you create a file handle.
·
A
file handle is a pointer associated with the open file that you can then
use to access the file ’ s contents.
·
When
you ’ ve finished with the file, you close it, which removes the file handle
from memory.
·
File handles are resource data types.
Opening a File with
fopen()
The
fopen() function opens a file and returns a file handle associated with the
file. For example
$handle
= fopen( “./data.txt”, “r” );
$handle
= fopen( “http://www.example.com/index.html”, “r” );
(PHP will look for the file in the
current directory, or it can be a relative ( ” ./data.txt “ ) or absolute ( “
/myfiles/data.txt “ ) path to a file.)
The
first argument can be just a filename
The
second argument specifies the mode as below
Closing
a File with fclose()
Once
you ’ ve finished working with a file, it needs to be closed. You can do this
using fclose()
fclose(
$handle );
<!DOCTYPE html>
<html>
<body>
<?php
$myfile =
fopen("webdictionary.txt", "r") or die("Unable to open
file!");
echo
fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
</body>
</html>
Reading and Writing to Files
Reading
and Writing Strings of Characters
fread() — Reads a string
of characters from a file
It
takes two arguments: a file handle and the number of characters to read.
$handle
= fopen( “data.txt”, “r” );
$data
= fread( $handle, 10 );
This
code reads the first ten characters from data.txt and assigns them to $data as
a string.
fwrite() — Writes a string
of characters to a file
It
requires two arguments: a file handle and a string to write to the file
$handle
= fopen( “data.txt”, “w” );
fwrite(
$handle, “ABCxyz” );
The
first line opens the file data.txt for writing, which erases any existing data
in the file. (If the file doesn ’ t exist, PHP attempts to create it.) The
second line writes the character string “ ABCxyz ” to the beginning of the
file.
fgetc() — Reads a single
character at a time
Testing
for the End of a File
feof() — Checks to see if
the end of the file has been reached
It
takes just one argument — the file handle to test. Notice that feof() only
returns true once the script has tried to read one or more characters past the
last character in the file:
// hello_world.txt contains the
characters “Hello, world!”
$handle = fopen( “hello_world.txt”,
“r” );
$text = “ ”;
while ( !feof( $handle ) )
{
$text .= fread( $handle, 3 ); // Read 3 chars at a
time
}
echo $text . “ < br / > ”; // Displays “Hello, world!”
fclose( $handle );
Reading
One Line at a Time
fgets() — Reads a single
line at a time
The following example uses fgets() to read and display a three - line text file, one line at a time. The while loop exits when fgets() returns false (which means it ’ s reached the end of the file):
/*
milton.txt contains:
The mind is its own place, and in it self
Can make a Heav’n of Hell, a Hell of Heav’n.
What matter where, if I be still the same,*/
$handle = fopen( “milton.txt”, “r” );
$lineNumber = 1;
while ( $line = fgets( $handle ) )
{
echo $lineNumber++ . “: $line <
br/> ”;
}
fclose( $handle );
Output:
1.The mind is its own place, and in it self
2.Can make a Heav’n of Hell, a Hell of Heav’n.
3.What matter where, if I be still the same
Reading CSV Files
fgetcsv() — Reads a line of
comma - separated values
To
call the fgetcsv() function, pass it the file handle of an open file. You can
also optionally specify:
·
The
maximum number of characters to read. You can leave this value out, or use 0,
in which case PHP reads as many characters as necessary to read the whole line.
However, specifying a value makes the function slightly quicker
·
The
delimiter that is used to separate each data value. The default is the comma (
, ). If you ’ re reading a tab - separated - value (TSV) file, specify “ \t ”
(the tab character) for this argument instead
·
The
character that is used to enclose string values. The default is the double
quote ( “ )
·
The
character used to escape special characters. The default is the backslash ( \ )
/*
people.csv contains:
“John”,”Smith”,45
“Anna”,”Clark”,37
“Bill”,”Murphy”,32
*/
$handle = fopen( “people.csv”, “r”
);
while ( $record = fgetcsv( $handle,
1000 ) )
{
echo “Name: {$record[0]} {$record[1]},
Age: {$record[2]} <br/> ”;
}
fclose( $handle );
This
code displays:
Name:
John Smith, Age: 45
Name:
Anna Clark, Age: 37
Name:
Bill Murphy, Age: 32
Reading
and Writing Entire Files
file() — Reads an entire
file into an array without needing to open it. The
function automatically opens, reads, and, once it ’ s done, closes the file.
It
takes just one argument — a string containing the name of the file to read —
and returns the array containing the lines of the file:
$lines
= file( “/home/chris/myfile.txt” );
file_get_contents() — Reads an entire
file into a string without needing to open it .The end - of - line characters
are included in the string:
$fileContents
= file_get_contents( “myfile.txt” );
file_put_contents() — Writes a whole
string to a file without needing to open it
it
takes a string and writes it to a file:
$numChars
= file_put_contents( “myfile.txt”, $myString );
fpassthru() — Displays the
contents of an open file.
$numChars
= fpassthru( $handle );
readfile() — Displays the
contents of a file without needing to open it.
$numChars = readfile( “myfile.txt” );
Random
Access to File Data
fseek() — Moves the file
pointer to a specific location within an open file
//
hello_world.txt contains the characters “Hello, world!”
$handle
= fopen( “hello_world.txt”, “r” );
fseek(
$handle, 7 );
echo
fread( $handle, 5 ); // Displays “world”
fclose(
$handle );
rewind()
--If
you want to move the pointer back to the start of the file (a common
occurrence), a handy shortcut is the rewind() function. The following two lines
of code both do the same thing:
fseek(
$handle, 0 );
rewind(
$handle );
ftell() —The ftell()
function takes a file handle and returns the current offset (in characters) of
the corresponding file pointer from the start of the file. For example:
$offset
= ftell( $handle );
Copying, Renaming, and Deleting Files
The
copy()
function takes two string arguments: the first argument is the path to the file
to copy, and the second argument is the path to copy it to. It returns true if
the file was successfully copied, or false if there was a problem copying the
file.
copy(
“./copyme.txt”, “./copied.txt” );
The
rename()
function is used to rename (or move) a file. It works in much the same way as
copy() .
For
example, to rename a file within a folder you could use:
rename(
“./address.dat”, “./address.backup” );
To
move a file to a different folder, you might use:
rename(
“/home/joe/myfile.txt”, “/home/joe/archives/myfile.txt” );
The
unlink()
function lets you delete files from the server. To use it, pass the filename of
the file you want to delete.
unlink(
“./trash.txt” );
Working with Directories
A
directory handle is similar to a file handle; it ’ s a special variable
pointing to a directory, which you can obtain via the opendir() function:
$handle
= opendir( “/home/james” );
If
there ’ s a problem opening the directory (for example, if the directory doesn
’ t exist), opendir() returns false instead of the directory handle.
you
can close a directory by passing the directory handle to the function closedir()
:
closedir( $handle
);
The readdir() function expects a
directory handle for an opened directory, and returns the filename of the next
entry in the directory:
$filename =
readdir( $handle );
Each directory
contains a list of entries for each of the files and subdirectories inside it, as
well as entries for . (representing the directory) and .. (the parent of the
directory). PHP maintains an internal pointer referring to the next entry in
the list, just as a file pointer points to the position in a file where the
next file operation should occur.
<?php
$dirPath
= “/home/matt/images”;
if
(!( $handle = opendir( $dirPath))) die(“Cannot open the directory.”);
?>
<p><?php
echo $dirPath ?> contains the following files and folders:</p>
<ul>
<?php
while
($file = readdir($handle)) {
if
( $file != “.” && $file != “..” )
echo
“<li>$file</li>”;
}
closedir(
$handle );
?>
Other
Directory Functions
Resetting the Directory Pointer
The rewinddir() function resets
PHP ’ s internal pointer back to the first entry in a given directory. To use
rewinddir() , pass an open directory handle to it, as follows:
rewinddir(
$handle );
Changing
the Current Directory
The
chdir() function call changes the current directory to a new directory:
chdir(
“/home/matt/myfolder” );
Creating
Directories
To
create a new directory, call the mkdir() function, passing in the path of the
directory you want to create:
mkdir(
“/home/matt/newfolder” );
You
can also set permissions for the directory at the time you create it by passing
the mode as the second argument. For example, the following code creates a
directory with read, write, and execute permissions granted to all users:
mkdir(
“/home/matt/newfolder”, 0777 );
Deleting
Directories
The
rmdir() function removes a given directory. The directory must be empty, and
you need appropriate permissions to remove it. For example:
rmdir(
“/home/matt/myfolder” );
Getting
the Directory Path
The
dirname() function returns the directory part of a given path.
For
example:
$path
= “/home/james/docs/index.html”;
$directoryPath
= dirname( $path );
$filename
= basename( $path );
After
running this code., $directoryPath contains “ /home/james/docs ” , and
$filename holds “ index.html ”.
Working
with Directory Objects
PHP
offers an alternative object - oriented mechanism for working with directories:
the Directory class.
To
use it, first create a Directory object by calling the dir() function with the
name of the directory you want to work with, as follows:
$dir
= dir( “/home/james/docs” );
The
Directory object provides two properties: handle and path . These refer to the
directory handle and the path to the directory, respectively:
echo
$dir- > handle . “ < br / > ”; // Displays the directory handle
echo
$dir- > path . “ < br / > ”; // Displays “/home/james/docs”
Telling
a File from a Directory
PHP
has two functions to help you test for a file or a directory:
is_dir() — Returns true if
the given filename refers to a directory
is_file() — Returns true if
the given filename refers to a regular file
Here
’ s a simple example that determines if a file called myfile is a file or a
directory:
$filename = “myfile”;
if ( is_dir( $filename ) ) {
echo “$filename is a directory.”;
} elseif ( is_file( $filename ) ) {
echo “$filename is a file.”;
} else {
echo “$filename is neither a
directory nor a file.”;
}
No comments:
Post a Comment