SlideShare a Scribd company logo
Files:
Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the file
name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Mode Purpose
r
Opens the file for reading only.
Places the file pointer at the beginning of the file.
r+
Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
w
Opens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
w+
Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
a
Opens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
a+
Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file
pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function.
The fclose() function requires a file pointer as its argument and then returns true when the
closure succeeds or false if it fails.
Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
Note: You cannot read from files opened in w, a, and x mode!
if (feof($file)) echo "End of file";
Reading a File Line by Line
The fgets() function is used to read a single line from a file.
Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
Reading a File Character by Character
The fgetc() function is used to read a single character from a file.
Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
Reading a file
Once a file is opened using fopen() function it can be read with a function called fread(). This
function requires two arguments. These must be the file pointer and the length of the file
expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
Open a file using fopen() function.
Get the file's length using filesize() function.
Read the file's content using fread() function.
Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those contents
on the web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>
<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
</body>
</html>
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite()
function. This function requires two arguments specifying a file pointer and the string of data
that is to be written. Optionally a third integer argument can be included to specify the length of
the data to write. If the third argument is included, writing would will stop after the specified
length has been reached.
The following example creates a new text file then writes a short text heading insite it. After
closing this file its existence is confirmed using file_exist() function which takes file name as an
argument
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple testn" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
<?php
if( file_exist( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
{
echo ("File $filename does not exit" );
}
?>
</body>
</html>
The filesystem functions are used to access and manipulate the filesystem PHP provides you all
the posible functions you may need to manipulate a file.
Installation:
The error and logging functions are part of the PHP core. There is no installation needed to use
these functions.
Runtime Configuration:
The behaviour of these functions is affected by settings in php.ini.
Name Default Changeable Changelog
allow_url_fopen "1" PHP_INI_ALL
PHP_INI_ALL in PHP <= 4.3.4.
PHP_INI_SYSTEM in PHP < 6.
Available since PHP 4.0.4.
allow_url_include "0" PHP_INI_ALL
PHP_INI_SYSTEM in PHP 5. Available
since PHP 5.2.0.
user_agent NULL PHP_INI_ALL Available since PHP 4.0.3.
default_socket_timeout "60" PHP_INI_ALL Available since PHP 4.3.0.
from "" PHP_INI_ALL
auto_detect_line_endings "0" PHP_INI_ALL Available since PHP 4.3.0.
PHP Error and Logging Constants:
PHP: indicates the earliest version of PHP that supports the constant.
You can use any of the constant while configuring your php.ini file.
Constant Description PHP
GLOB_BRACE
GLOB_ONLYDIR
GLOB_MARK
GLOB_NOSORT
GLOB_NOCHECK
GLOB_NOESCAPE
PATHINFO_DIRNAME
PATHINFO_BASENAME
PATHINFO_EXTENSION
PATHINFO_FILENAME 5.2.0
FILE_USE_INCLUDE_PATH Search for filename in include_path 5.0.0
FILE_APPEND Append content to existing file.
FILE_IGNORE_NEW_LINES Strip EOL characters 5.0.0
FILE_SKIP_EMPTY_LINES Skip empty lines 5.0.0
FILE_BINARY Binary mode 6.0.0
FILE_TEXT Text mode 6.0.0
List of Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
basename() Returns filename component of path 3
chgrp() Changes file group 3
chmod() Changes file mode 3
chown() Changes file owner 3
clearstatcache() Clears file status cache 3
copy() Copies file 3
delete() Deletes file
dirname() Returns directory name component of path 3
disk_free_space() Returns available space in directory 4.0.7
disk_total_space() Returns the total size of a directory 4.0.7
diskfreespace() Alias of disk_free_space() 4.0.7
fclose() Closes an open file pointer 3
feof() Tests for end-of-file on a file pointer 3
fflush() Flushes the output to a file 4
fgetc() Gets character from file pointer 3
fgetcsv() Gets line from file pointer and parse for CSV fields 3
fgets() Gets line from file pointer 3
fgetss() Gets line from file pointer and strip HTML tags 3
file_exists() Checks whether a file or directory exists 3
file_get_contents() Reads entire file into a string 4.3.0
file_put_contents() Write a string to a file 5
file() Reads entire file into an array 3
fileatime() Gets last access time of file 3
filectime() Gets inode change time of file 3
filegroup() Gets file group 3
fileinode() Gets file inode 3
filemtime() Gets file modification time 3
fileowner() Gets file owner 3
fileperms() Gets file permissions 3
filesize() Gets file size 3
filetype() Gets file type 3
flock() Portable advisory file locking 3
fnmatch() Match filename against a pattern 4.0.3
fopen() Opens file or URL 3
fpassthru() Output all remaining data on a file pointer 3
fputcsv() Format line as CSV and write to file pointer 5.1.0
fputs() Alias of fwrite() 3
fread() Binary-safe file read 3
fscanf() Parses input from a file according to a format 4.0.1
fseek() Seeks on a file pointer 3
fstat() Gets information about a file using an open file pointer 4
ftell() Tells file pointer read/write position 3
ftruncate() Truncates a file to a given length 4
fwrite() Binary-safe file write 3
glob() Find pathnames matching a pattern 4.0.3
is_dir() Tells whether the filename is a directory 3
is_executable() Tells whether the filename is executable 3
is_file() Tells whether the filename is a regular file 3
is_link() Tells whether the filename is a symbolic link 3
is_readable() Tells whether the filename is readable 3
is_uploaded_file() Tells whether the file was uploaded via HTTP POST 4.0.3
is_writable() Tells whether the filename is writable 3
is_writeable() Alias of is_writable() 3
lchgrp() Changes group ownership of symlink 5.1.2
lchown() Changes user ownership of symlink 5.1.2
link() Create a hard link 3
linkinfo() Gets information about a link 3
lstat() Gives information about a file or symbolic link 3
mkdir() Makes directory 3
move_uploaded_file() Moves an uploaded file to a new location 4.0.3
parse_ini_file() Parse a configuration file 4
pathinfo() Returns information about a file path 4.0.3
pclose() Closes process file pointer 3
popen() Opens process file pointer 3
readfile() Outputs a file 3
readlink() Returns the target of a symbolic link 3
realpath() Returns canonicalized absolute pathname 4
rename() Renames a file or directory 3
rewind() Rewind the position of a file pointer 3
rmdir() Removes directory 3
set_file_buffer() Alias of stream_set_write_buffer() 3
stat() Gives information about a file 3
symlink() Creates a symbolic link 3
tempnam() Create file with unique file name 3
tmpfile() Creates a temporary file 3
touch() Sets access and modification time of file 3
umask() Changes the current umask 3
unlink() Deletes a file 3
List of All File functions in php
Introduction
If you were having trouble in remembering all file related functions of PHP, then don't worry,
I'm publishing here a full list of all of them, so that you can easily use any of them. File system
related functions were divided into 9 extensions of php whose names are shown below.
List of File system related extensions
Click on links to directly Jump on page section.
1. Direct IO,
2. Directories,
3. Fileinfo,
4. Filesystem,
5. Inotify,
6. Mimetype (No functions found),
7. Proctile,
8. Xattr,
9. And xdiff.
Filesystem functions in php
Function Name Description Syntax Other information
Function Name Description Syntax Other information
basename
Given a string containing the
path to a file or directory, this
function will return the
trailing name component.
basename ( string $path [,
string $suffix ] )
chgrp Changes file group
chgrp ( string $filename ,
mixed $group )
group - A group name or
number.
chmod
Attempts to change the mode
of the specified file to that
given in $mode.
chmod ( string $filename ,
int $mode )
Returns TRUE on success
or FALSE on failure.
chown
Attempts to change the
owner of the file $filename to
$user user. Only the
superuser may change the
owner of a file.
chown ( string $filename ,
mixed $user )
filename - path to the file,
user - A user name or
number.
clearstatcache Clears file status cache
clearstatcache ([ bool
$clear_realpath_cache =
false [, string $filename ]] )
clear_realpath_cache -
Whether to clear the
realpath cache or not.
copy
Makes a copy of the file
$source to $dest.
copy ( string $source ,
string $dest [, resource
$context ] )
Returns TRUE on success
or FALSE on failure.
delete
This is a dummy manual entry
to satisfy those people who
are looking for unlink() or
unset() in the wrong place.
delete ( void )
dirname
Given a string containing the
path of a file or directory, this
function will return the parent
directory's path.
dirname ( string $path )
disk_free_space
Given a string containing a
directory, this function will
return the number of bytes
available on the
corresponding filesystem or
disk partition.
disk_free_space ( string
$directory )
Function Name Description Syntax Other information
disk_total_space
Given a string containing a
directory, this function will
return the total number of
bytes on the corresponding
filesystem or disk partition.
disk_total_space ( string
$directory )
Returns the total number
of bytes as a float or
FALSE on failure.
diskfreespace
This function is an alias of:
disk_free_space().
fclose
The file pointed to by handle
is closed.
fclose ( resource $handle )
handle - The file pointer
must be valid, and must
point to a file successfully
opened by fopen() or
fsockopen().
feof
Tests for end-of-file on a file
pointer.
feof ( resource $handle )
The file pointer must be
valid, and must point to a
file successfully opened
by fopen() or fsockopen()
(and not yet closed by
fclose()).
fflush
This function forces a write of
all buffered output to the
resource pointed to by the file
handle.
fflush ( resource $handle )
Returns TRUE on success
or FALSE on failure.
fgetc
Gets a character from the
given file pointer.
fgetc ( resource $handle )
Returns a string
containing a single
character read from the
file pointed to by handle.
Returns FALSE on EOF.
fgetcsv
Similar to fgets() except that
fgetcsv() parses the line it
reads for fields in CSV format
and returns an array
containing the fields read.
fgetcsv ( resource $handle
[, int $length = 0 [, string
$delimiter = ',' [, string
$enclosure = '"' [, string
$escape = '' ]]]] )
handle - A valid file
pointer to a file
successfully opened by
fopen(), popen(), or
fsockopen().
fgets Gets a line from file pointer.
fgets ( resource $handle [,
int $length ] )
length - If no length is
specified, it will keep
reading from the stream
Function Name Description Syntax Other information
until it reaches the end of
the line.
fgetss
Identical to fgets(), except
that fgetss() attempts to strip
any NUL bytes, HTML and PHP
tags from the text it reads.
fgetss ( resource $handle [,
int $length [, string
$allowable_tags ]] )
allowable_tags - You can
use the optional third
parameter to specify tags
which should not be
stripped.
file_exists
Checks whether a file or
directory exists.
file_exists ( string
$filename )
file_get_contents Reads entire file into a string
file_get_contents ( string
$filename [, bool
$use_include_path = false
[, resource $context [, int
$offset = -1 [, int $maxlen
]]]] )
file_put_contents
This function is identical to
calling fopen(), fwrite() and
fclose() successively to write
data to a file.
file_put_contents ( string
$filename , mixed $data [,
int $flags = 0 [, resource
$context ]] )
file
Reads an entire file into an
array.
file ( string $filename [, int
$flags = 0 [, resource
$context ]] )
fileatime
Gets the last access time of
the given file.
fileatime ( string $filename
)
filectime
Gets the inode change time of
a file.
filectime ( string $filename
)
filegroup
Gets the file group. The group
ID is returned in numerical
format, use posix_getgrgid()
to resolve it to a group name.
filegroup ( string $filename
)
fileinode Gets the file inode.
fileinode ( string $filename
)
Returns the inode number
of the file, or FALSE on
failure.
Function Name Description Syntax Other information
filemtime
This function returns the time
when the data blocks of a file
were being written to, that is,
the time when the content of
the file was changed.
filemtime ( string
$filename )
Returns the time the file
was last modified, or
FALSE on failure. The time
is returned as a Unix
timestamp, which is
suitable for the date()
function.
fileowner Gets the file owner.
fileowner ( string
$filename )
Returns the user ID of the
owner of the file, or FALSE
on failure. The user ID is
returned in numerical
format, use
posix_getpwuid() to
resolve it to a username.
fileperms
Gets permissions for the given
file.
fileperms ( string
$filename )
Returns the permissions
on the file, or FALSE on
failure.
filesize Gets the size for the given file.filesize ( string $filename )
filetype
Returns the type of the given
file.
filetype ( string $filename )
Returns the type of the
file. Possible values are
fifo, char, dir, block, link,
file, socket and unknown.
flock Portable advisory file locking
flock ( resource $handle ,
int $operation [, int
&$wouldblock ] )
fnmatch
Match filename against a
pattern
fnmatch ( string $pattern ,
string $string [, int $flags =
0 ] )
fopen Opens file or URL
fopen ( string $filename ,
string $mode [, bool
$use_include_path = false
[, resource $context ]] )
fpassthru
Output all remaining data on
a file pointer
fpassthru ( resource
$handle )
Function Name Description Syntax Other information
fputcsv
Format line as CSV and write
to file pointer
fputcsv ( resource $handle
, array $fields [, string
$delimiter = ',' [, string
$enclosure = '"' ]] )
fputs
This function is an alias of:
fwrite().
fread Binary-safe file read
fread ( resource $handle ,
int $length )
fscanf
Parses input from a file
according to a format
fscanf ( resource $handle ,
string $format [, mixed
&$... ] )
fseek Seeks on a file pointer
fseek ( resource $handle ,
int $offset [, int $whence =
SEEK_SET ] )
fstat
Gets information about a file
using an open file pointer
fstat ( resource $handle )
handle - A file system
pointer resource that is
typically created using
fopen().
ftell
Returns the position of the
file pointer referenced by
handle.
ftell ( resource $handle )
ftruncate
Truncates a file to a given
length
ftruncate ( resource
$handle , int $size )
fwrite Binary-safe file write
fwrite ( resource $handle ,
string $string [, int $length
] )
glob
Find pathnames matching a
pattern
glob ( string $pattern [, int
$flags = 0 ] )
is_dir
Tells whether the given
filename is a directory.
is_dir ( string $filename )
is_executable
Tells whether the filename is
executable.
is_executable ( string
$filename )
Function Name Description Syntax Other information
is_file
Tells whether the given file is
a regular file.
is_file ( string $filename )
is_link
Tells whether the given file is
a symbolic link.
is_link ( string $filename )
is_readable
Tells whether a file exists and
is readable.
is_readable ( string
$filename )
is_uploaded_file
Tells whether the file was
uploaded via HTTP POST
is_uploaded_file ( string
$filename )
is_writable
Tells whether the filename is
writable
is_writable ( string
$filename )
is_writeable
This function is an alias of:
is_writable().
lchgrp
Changes group ownership of
symlink
lchgrp ( string $filename ,
mixed $group )
lchown
Changes user ownership of
symlink
lchown ( string $filename ,
mixed $user )
link link() creates a hard link.
link ( string $target , string
$link )
linkinfo Gets information about a link linkinfo ( string $path )
lstat
Gives information about a file
or symbolic link
lstat ( string $filename )
mkdir
Attempts to create the
directory specified by
pathname.
mkdir ( string $pathname
[, int $mode = 0777 [, bool
$recursive = false [,
resource $context ]]] )
move_uploaded_file
Moves an uploaded file to a
new location
move_uploaded_file (
string $filename , string
$destination )
parse_ini_file Parse a configuration file
parse_ini_file ( string
$filename [, bool
$process_sections = false
Function Name Description Syntax Other information
[, int $scanner_mode =
INI_SCANNER_NORMAL ]]
)
parse_ini_string Parse a configuration string
parse_ini_string ( string
$ini [, bool
$process_sections = false
[, int $scanner_mode =
INI_SCANNER_NORMAL ]]
)
pathinfo
pathinfo() returns an
associative array containing
information about path.
pathinfo ( string $path [,
int $options =
PATHINFO_DIRNAME |
PATHINFO_BASENAME |
PATHINFO_EXTENSION |
PATHINFO_FILENAME ] )
pclose
Closes a file pointer to a pipe
opened by popen().
pclose ( resource $handle )
Returns the termination
status of the process that
was run. In case of an
error then -1 is returned.
popen Opens process file pointer
popen ( string $command ,
string $mode )
readfile Outputs a file
readfile ( string $filename
[, bool $use_include_path
= false [, resource $context
]] )
readlink
Returns the target of a
symbolic link
readlink ( string $path )
realpath_cache_get
Get the contents of the
realpath cache.
realpath_cache_get ( void
)
Returns an array of
realpath cache entries.
The keys are original path
entries, and the values are
arrays of data items,
containing the resolved
path, expiration date, and
other options kept in the
Function Name Description Syntax Other information
cache.
realpath_cache_size
Get the amount of memory
used by the realpath cache.
realpath_cache_size ( void
)
realpath
Returns canonicalized
absolute pathname
realpath ( string $path )
rename
Attempts to rename oldname
to newname.
rename ( string $oldname ,
string $newname [,
resource $context ] )
rewind
Sets the file position indicator
for handle to the beginning of
the file stream.
rewind ( resource $handle
)
rmdir Removes directory
rmdir ( string $dirname [,
resource $context ] )
set_file_buffer
This function is an alias of:
stream_set_write_buffer().
stat Gives information about a file stat ( string $filename )
symlink Creates a symbolic link
symlink ( string $target ,
string $link )
tempnam
Create file with unique file
name
tempnam ( string $dir ,
string $prefix )
Returns the new
temporary filename, or
FALSE on failure.
tmpfile
Creates a temporary
fileCreates a temporary file
with a unique name in read-
write (w+) mode and returns
a file handle .
tmpfile ( void )
touch
Sets access and modification
time of file
touch ( string $filename [,
int $time = time() [, int
$atime ]] )
umask Changes the current umask umask ([ int $mask ] )
unlink Deletes a file unlink ( string $filename [, Returns TRUE on success
Function Name Description Syntax Other information
resource $context ] ) or FALSE on failure.
Direct IO functions in php
Function
Name
Description Syntax Other Information
dio_close Closes the file description given by fd dio_close(resource $fd)
fd - The file descriptor
returned by dio_open()
dio_fcntl
The dio_fcntl() function performs the
operation specified by cmd on the file
descriptor fd. Some commands require
additional arguments args to be
supplied.
dio_fcntl ( resource $fd ,
int $cmd [, mixed $args ] )
cmd - can be F_SETLK,
F_SETLKW, F_GETLK,
F_DUPFD, F_SETFL
dio_open
dio_open() opens a file and returns a
new file descriptor for it.
dio_open ( string
$filename , int $flags [, int
$mode = 0 ] )
filename - Path of the
file to open.
dio_read
The function dio_read() reads and
returns len bytes from file with
descriptor fd.
string dio_read ( resource
$fd [, int $len = 1024 ] )
len - Number of Bytes to
read.
dio_seek
The function dio_seek() is used to
change the file position of the given
file descriptor.
dio_seek ( resource $fd ,
int $pos [, int $whence =
SEEK_SET ] )
pos - The new position,
Whence -Specifies how
the position pos should
be interpreted.
dio_stat
dio_stat() returns information about
the given file descriptor.
dio_stat ( resource $fd )
fd - The file descriptor
returned by dio_open().
dio_tcsetattr
dio_tcsetattr() sets the terminal
attributes and baud rate of the open
fd.
dio_tcsetattr ( resource
$fd , array $options )
Currently available
options are 'baud' , 'bits',
'stop', 'parity'.
dio_truncate
dio_truncate() truncates a file to at
most offset bytes in size.
The offset in bytes.
Returns TRUE on success
or FALSE on failure.
dio_write
dio_write() writes up to len bytes from
data to file fd.
int dio_write ( resource
$fd , string $data [, int
$len = 0 ] )
data - The written data.
Directory functions in PHP
Function
Name
Description Syntax Other Information
chdir
Changes PHP's current
directory to new directory.
chdir ( string $directory
)
directory - The new current directory
chroot
Changes the root directory of
the current process to
directory, and changes the
current working directory to
"/".
chroot ( string
$directory )
directory - The path to change the root
directory to.
dir
Return an instance of the
Directory class
-
object-oriented mechanism (search
google)
closedir
Closes the directory stream
indicated by dir_handle. The
stream must have previously
been opened by opendir().
closedir ([ resource
$dir_handle ] )
dir_handle - The directory handle
resource previously opened with
opendir(). If the directory handle is not
specified, the last link opened by
opendir() is assumed.
getcwd
Gets the current working
directory.
getcwd ( )
Returns the current working directory
on success, or FALSE on failure.
opendir
Opens up a directory handle to
be used in subsequent
closedir(), readdir(), and
rewinddir() calls.
opendir ( string $path [,
resource $context ] )
path - The directory path that is to be
opened
readdir
Returns the filename of the
next file from the directory.
The filenames are returned in
the order in which they are
stored by the filesystem.
readdir ([ resource
$dir_handle ] )
Returns the filename on success or
FALSE on failure.
rewinddir
Resets the directory stream
indicated by dir_handle to the
beginning of the directory.
rewinddir ([ resource
$dir_handle ] )
scandir
Returns an array of files and
directories from the directory.
scandir ( string
$directory [, int
$sorting_order = 0 [,
sorting_order - By default, the sorted
order is alphabetical in ascending
order. If the optional sorting_order is
Function
Name
Description Syntax Other Information
resource $context ]] ) set to non-zero, then the sort order is
alphabetical in descending order.
Fileinfo functions in PHP
Function Name Description Syntax Other Information
finfo_buffer
This function is
used to get
information about
binary data in a
string.
finfo_buffer ( resource
$finfo , string $string =
NULL [, int $options =
FILEINFO_NONE [,
resource $context = NULL
]] )
finfo - Fileinfo resource returned by
finfo_open(), $string - Content of a
file to be checked,
finfo_close
This function closes
the resource
opened by
finfo_open().
finfo_close ( resource
$finfo )
finfo - Fileinfo resource returned by
finfo_open().
finfo_file
This function is
used to get
information about
a file.
finfo_file ( resource $finfo
, string $file_name = NULL
[, int $options =
FILEINFO_NONE [,
resource $context = NULL
]] )
file_name - Name of a file to be
checked.
finfo_open
This function opens
a magic database
and returns its
resource.
finfo_open ([ int $options
= FILEINFO_NONE [, string
$magic_file = NULL ]] )
Name of a magic database file,
usually something like
/path/to/magic.mime. If not
specified, the MAGIC environment
variable is used. If this variable is not
set either, /usr/share/misc/magic is
used by default. A .mime and/or .mgc
suffix is added if needed.
finfo_set_flags
This function sets
various Fileinfo
options. Options
can be set also
directly in
finfo_set_flags ( resource
$finfo , int $options )
Returns TRUE on success or FALSE on
failure.
Function Name Description Syntax Other Information
finfo_open() or
other Fileinfo
functions.
mime_content_type
Returns the MIME
content type for a
file as determined
by using
information from
the magic.mime
file.
mime_content_type (
string $filename )
filename - Path to the tested file.
Inotify functions in PHP
Function Name Description Syntax Other Information
inotify_add_watch
inotify_add_watch() adds a new
watch or modify an existing watch
for the file or directory specified in
pathname.
inotify_add_watch (
resource
$inotify_instance , string
$pathname , int $mask )
inotify_instance -
Resource returned by
inotify_init()
inotify_init
Initialize an inotify instance for use
with inotify_add_watch()
inotify_init ( void )
inotify_queue_len
This function allows to know if
inotify_read() will block or not. If a
number upper than zero is returned,
there are pending events and
inotify_read() will not block.
inotify_queue_len (
resource
$inotify_instance )
inotify_read
Read inotify events from an inotify
instance.
inotify_read ( resource
$inotify_instance )
inotify_rm_watch
Remove an existing watch from an
inotify instance
inotify_rm_watch (
resource
$inotify_instance , int
$watch_descriptor )
watch_descriptor -
Watch to remove
from the instance
Proctile functions in PHP
Function
Name
Description Syntax Other Information
setproctitle
Sets the process title of the
current process.
setproctitle ( string
$title )
title - The title to use as the
process title.
setthreadtitle Sets the thread title.
setthreadtitle ( string
$title )
Returns TRUE on success or
FALSE on failure.
xattr functions of php
Function Name Description Syntax Other Information
xattr_get
This function gets the value of an
extended attribute of a file.
xattr_get ( string $filename
, string $name [, int $flags =
0 ] )
filename - The file from
which we get the
attribute, name - The
name of the attribute.
xattr_list
This functions gets a list of names
of extended attributes of a file.
xattr_list ( string $filename
[, int $flags = 0 ] )
filename - The path of the
file.
xattr_remove
This function removes an
extended attribute of a file.
xattr_remove ( string
$filename , string $name [,
int $flags = 0 ] )
xattr_set
This function sets the value of an
extended attribute of a file.
xattr_set ( string $filename
, string $name , string
$value [, int $flags = 0 ] )
value - The value of the
attribute
xattr_supported
This functions checks if the
filesystem holding the given file
supports extended attributes.
Read access to the file is
required.
xattr_supported ( string
$filename [, int $flags = 0 ]
)
filename - The path of the
tested file.
xdiff functions in PHP
Function Name Description Syntax Other Information
xdiff_file_bdiff_size Returns a size of a
result file that would
xdiff_file_bdiff_size ( string
file - The path to the
binary patch created by
Function Name Description Syntax Other Information
be created after
applying binary patch
from file file to the
original file.
$file ) xdiff_string_bdiff() or
xdiff_string_rabdiff()
function.
xdiff_file_bdiff
Make binary diff of
two files
xdiff_file_bdiff ( string
$old_file , string $new_file ,
string $dest )
dest - Path of the
resulting patch file.
Resulting file contains
differences between "old"
and "new" files. It is in
binary format and is
human-unreadable.
xdiff_file_bpatch
Patch a file with a
binary diff
xdiff_file_bpatch ( string
$file , string $patch , string
$dest )
dest - Path of the
resulting file, patch - The
binary patch file.
xdiff_file_diff_binary Alias of xdiff_file_bdiff
xdiff_file_diff_binary ( string
$old_file , string $new_file ,
string $dest )
xdiff_file_diff
Make unified diff of
two files
xdiff_file_diff ( string
$old_file , string $new_file ,
string $dest [, int $context =
3 [, bool $minimal = false ]] )
xdiff_file_merge3 Merge 3 files into one
xdiff_file_merge3 ( string
$old_file , string $new_file1 ,
string $new_file2 , string
$dest )
dest - Path of the
resulting file, containing
merged changed from
both new_file1 and
new_file2.
xdiff_file_patch_binary
Alias of
xdiff_file_bpatch
xdiff_file_patch_binary (
string $file , string $patch ,
string $dest )
xdiff_file_patch
Patch a file with an
unified diff
xdiff_file_patch ( string $file ,
string $patch , string $dest [,
int $flags =
DIFF_PATCH_NORMAL ] )
xdiff_file_rabdiff Make binary diff of
two files using the
xdiff_file_rabdiff ( string
$old_file , string $new_file ,
Function Name Description Syntax Other Information
Rabin's polynomial
fingerprinting
algorithm
string $dest )
xdiff_string_bdiff_size
Returns a size of a
result file that would
be created after
applying binary $patch
to the original file.
xdiff_string_bdiff_size (
string $patch )
patch - The binary patch
created by
xdiff_string_bdiff() or
xdiff_string_rabdiff()
function.
xdiff_string_bdiff
Make binary diff of
two strings
xdiff_string_bdiff ( string
$old_data , string
$new_data )
xdiff_string_bpatch
Patch a string with a
binary diff
xdiff_string_bpatch ( string
$str , string $patch )
xdiff_string_diff_binary
Alias of
xdiff_string_bdiff
xdiff_string_bdiff ( string
$old_data , string
$new_data )
xdiff_string_diff
Make unified diff of
two strings
xdiff_string_diff ( string
$old_data , string
$new_data [, int $context =
3 [, bool $minimal = false ]] )
xdiff_string_merge3
Merge 3 strings into
one
xdiff_string_merge3 ( string
$old_data , string
$new_data1 , string
$new_data2 [, string &$error
] )
xdiff_string_patch_binary
Alias of
xdiff_string_bpatch
xdiff_string_patch_binary (
string $str , string $patch )
xdiff_string_patch
Patch a string with an
unified diff
xdiff_string_patch ( string
$str , string $patch [, int
$flags [, string &$error ]] )
xdiff_string_rabdiff
Make binary diff of
two strings using the
Rabin's polynomial
fingerprinting
xdiff_string_bdiff ( string
$old_data , string
$new_data )
Function Name Description Syntax Other Information
algorithm
John Donne famously said, “No man is an island,” and this maxim holds true for PHP
scripts as well. So far, all the examples you’ve seen have been self-contained, with their
source data arriving either from user input or from variables hard-wired into the program
body. In reality, though, your PHP script will need to work with data retrieved from disk
files, SQL resultsets, XML documents, and many other data sources.
PHP comes with numerous built-in functions to access these data sources and this
chapter will get you started on the road to discovering them, by focusing specifically on
PHP’s file system functions. With 70+ functions available, there’s an abundance of options;
this chapter will give you a crash course in the most important ones, with both examples
and practical projects of reading, writing, and manipulating disk files and directories.
Reading Files
PHP’s file manipulation API is extremely flexible: it lets you read files into a string or into
an array, from the local file system or a remote URL, by lines, bytes, or characters. The
following sections explain all these variants in greater detail.
Reading Local Files
The easiest way to read the contents of a disk file in PHP is with the file_get_
contents() function. This function accepts the name and path to a disk file, and reads
the entire file into a string variable in one fell swoop. Here’s an example:
<?php
// read file into string
$str = file_get_contents('example.txt') or die('ERROR: Cannot find file');
echo $str;
?>
An alternative method of reading data from a file is PHP’s file() function, which
accepts the name and path to a file and reads the entire file into an array, with each
element of the array representing one line of the file. To process the file, all you need do is
iterate over the array using a foreach loop. Here’s an example, which reads a file into an
array and then displays it using such a loop:
<?php
// read file into array
$arr = file('example.txt') or die('ERROR: Cannot find file');
foreach ($arr as $line) {
echo $line;
}
?>
Reading Remote Files
Both file_get_contents() and file() also support reading data from URLs, using
either the HTTP or FTP protocol. Here’s an example, which reads an HTML file off the
Web into an array:
<?php
// read file into array
$arr = file('http://www.google.com') or die('ERROR: Cannot find file');
foreach ($arr as $line) {
echo $line;
}
?>
In case of slow network links, it’s sometimes more efficient to read a remote file in
“chunks,” to maximize the efficiency of available network bandwidth. To do this, use the
fgets() function to read a specific number of bytes from a file, as in the next example:
<?php
// read file into array (chunks)
$str = '';$fp = fopen('http://www.google.com', 'r') or die('ERROR:
Cannot open file');
while (!feof($fp)) {
$str .= fgets($fp,512);
}
fclose($fp);
echo $str;
?>
This listing introduces four new functions, so let’s take a closer look at it. First, the
fopen() function: it accepts the name of the source file and an argument indicating
whether the file is to be opened in read ('r'), write ('w'), or append ('a') mode,
and then creates a pointer to the file. Next, a while loop calls the fgets() function
continuously in a loop to read a specific number of bytes from the file and append these
bytes to a string variable; this loop continues until the feof() function returns true,
indicating that the end of the file has been reached. Once the loop has completed, the
fclose() function destroys the file pointer.
NOTE
In order to read remote URLs, the PHP configuration variable 'allow_url_fopen'
must be set to true in the PHP configuration file php.ini. If this variable is set to false, all
attempts to read remote files will fail.
Reading Specific Segments of a File
A final twist involves reading only a specific block of lines from a line—something that
can be accomplished with a combination of PHP’s fseek() and fgets() functions.
Consider the next example, which sets up a user-defined function named readBlock()
and accepts three arguments: the filename, the starting line number, and the number of
lines to return from the starting point:
<?php
// function definition
// read a block of lines from a file
function readBlock($file, $start=1, $lines=null) {
// open file
$fp = fopen($file, 'r') or die('ERROR: Cannot find file');
// initialize counters
$linesScanned = 1;
$linesRead = 0;
$out = '';
// loop until end of file
while (!feof($fp)) {
// get each line
$line = fgets($fp);
// if start position is reached
// append line to output variable
if ($linesScanned >= $start) {
$out .= $line;
$linesRead++;
// if max number of lines is defined and reached
// break out of loop
if (!is_null($linesRead) && $linesRead == ($lines)) {
break;
}
}
$linesScanned++;
}
return $out;
}
echo readBlock('example.txt', 3, 4);
?>
Within readBlock(), a loop iterates through the file line by line, until the starting
line number is reached (a line counter named $linesScanned keeps track of the current
line number, incrementing by 1 on each iteration of the loop). Once the starting line is
reached, it (and all subsequent lines) are read into a string variable until the specified
maximum number of lines are processed or until the end of the file is reached.
Writing Files
The flip side of reading data from files is writing data to them. And PHP comes with a
couple of different ways to do this as well. The first is the file_put_contents()
function, a close cousin of the file_get_contents() function you read about in the
preceding section: this function accepts a filename and path, together with the data to be
written to the file, and then writes the latter to the former. Here’s an example:
<?php
// write string to file
$data = "A fish n out of n watern";
file_put_contents('output.txt', $data)
or die('ERROR: Cannot write file');
echo 'Data written to file';
?>
If the file specified in the call to file_put_contents() already exists on disk,
file_put_contents() will overwrite it by default. If, instead, you’d prefer to preserve
the file’s contents and simply append new data to it, add the special FILE_APPEND flag to
your file_put_contents() function call as a third argument. Here’s an example:
<?php
// write string to file
$data = "A fish n out of n watern";
file_put_contents('output.txt', $data, FILE_APPEND)
or die('ERROR: Cannot write file');
echo 'Data written to file';
?>
An alternative way to write data to a file is to create a file pointer with fopen(), and
then write data to the pointer using PHP’s fwrite() function. Here’s an example of this
technique:
<?php
// open and lock file
// write string to file
// unlock and close file
$data = "A fish n out of n watern";
$fp = fopen('output.txt', 'w') or die('ERROR: Cannot open file');
flock($fp, LOCK_EX) or die ('ERROR: Cannot lock file');
fwrite($fp, $data) or die ('ERROR: Cannot write file');
flock($fp, LOCK_UN) or die ('ERROR: Cannot unlock file');
fclose($fp);
echo 'Data written to file';
?>
Notice the flock() function from the preceding listing: this function “locks” a file before reading or
writing it, so that it cannot be accessed by another process. Doing this reduces the possibility of data
corruption that might occur if two processes attempt to write different data to the same file at the
same instant. The second parameter to flock()specifies the type of lock: LOCK_EX creates an
exclusive lock for writing, LOCK_SH creates a non-exclusive lock for reading, and LOCK_UN
destroys the lock.
Q: Can I read and write binary files with PHP?
A: Yes. The file_get_contents(), file_put_contents(), and file() functions all read and
write data in binary format by default; this lets you use PHP with binary files without worrying that your
data will get corrupted.
NOTE
The directory into which you’re trying to save the file must already exist, or else PHP will generate a fatal error. You
can test if a directory exists with the file_exists()function.
his 6 -1 Reading and Writing Configuration Files
Now that you know how to read and write files, let’s try creating an application that
uses the functions described in the preceding section. Assume for a second that you’re
developing a Weblog application, and you’d like your users to be able to configure certain
aspects of this application’s behavior—for example, how many posts appear on the index
page or the e-mail address that comments are sent to. In this case, you’d probably need
to build a Web-based form that allows users to input these configuration values and saves
them to a file that your application can read as needed.
This next listing generates just such a Web form, allowing users to enter values for
different configuration values and then saving this information to a disk file. When users
revisit the form, the data previously saved to the file is read and used to prefill the form’s
fields.
Here’s the code (configure.php):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Project 6-1: Reading And Writing Configuration Files</title>
</head>
<body>
<h2>Project 6-1: Reading And Writing Configuration Files</h2>
<?php
// define configuration filename and path
$configFile = 'config.ini';
// if form not yet submitted
// display form
if (!isset($_POST['submit'])) {
// set up array with default parameters
$data = array();
$data['AdminEmailAddress'] = null;
$data['DefAuthor'] = null;
$data['NumPosts'] = null;
$data['NumComments'] = null;
$data['NotifyURL'] = null;
// read current configuration values
// use them to pre-fill the form
if (file_exists($configFile)) {
$lines = file($configFile);
foreach ($lines as $line) {
$arr = explode('=', $line);
$i = count($arr) - 1;
(continued)
$data[$arr[0]] = $arr[$i];
}
}
?>
<form method="post" action="configure.php">
Administrator email address: <br />
<input type="text" size="50" name="data[AdminEmailAddress]" value="<?php
echo $data['AdminEmailAddress']; ?>"/>
<p>
Default author name: <br />
<input type="text" name="data[DefAuthor]" value="<?php echo
$data['DefAuthor']; ?>"/>
<p>
Number of posts on index page: <br />
<input type="text" size="4" name="data[NumPosts]" value="<?php echo
$data['NumPosts']; ?>"/>
<p>
Number of anonymous comments: <br />
<input type="text" size="4" name="data[NumComments]" value="<?php echo
$data['NumComments']; ?>"/>
<p>
URL for automatic notification of new posts: <br />
<input type="text" size="50" name="data[NotifyURL]" value="<?php echo
$data['NotifyURL']; ?>"/>
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
// if form submitted
// process form input
} else {
// read submitted data
$config = $_POST['data'];
// validate submitted data as necessary
if ((trim($config['NumPosts']) != '' && (int)$config['NumPosts'] <= 0) ||
(trim($config['NumComments']) != '' && (int)$config['NumComments'] <= 0)) {
die('ERROR: Please enter a valid number');
}
// open and lock configuration file for writing
$fp = fopen($configFile, 'w+') or die('ERROR: Cannot open configuration
file for writing');
flock($fp, LOCK_EX) or die('ERROR: Cannot lock configuration file for
writing');
// write each configuration value to the file
foreach ($config as $key => $value) {
if (trim($value) != '') {
fwrite($fp, "$key=$valuen") or die('ERROR: Cannot write [$key] to
configuration file');
}
}
// close and save file
flock($fp, LOCK_UN) or die ('ERROR: Cannot unlock file');
fclose($fp);
echo 'Configuration data successfully written to file.';
}
?>
</body>
</html>
This example illustrates a common, and practical, use of PHP’s file functions: to read
and write configuration files in the context of a Web application. Figure 6-1 illustrates the
Web form generated by this script.
Once the form is submitted, the data entered into it arrives in the form of an associative
array, whose keys correspond to the configuration variables in use. This data is then validated
and a file pointer is opened to the configuration file, config.ini. A foreach loop then iterates
over the array, writing the keys and values to the file pointer in key=value format, with each
key-value pair on a separate line. The file pointer is then closed, saving the data to disk.
Figure 6-1 A Web form to enter configuration data
(continued)
Here’s an example of what config.ini would look like after submitting the form in
Figure 6-1:
AdminEmailAddress=admin@abc.com
DefAuthor=Charles W
NumPosts=8
NumComments=4
If a user revisits the Web form, the script first checks if a configuration file named
config.ini exists in the current directory. If it does, the lines of the file are read into an
array with PHP’s file() function; a foreach loop then processes this array, splitting
each line on the equality (=) symbol and turning the resulting key-value pairs into an
associative array. This array is then used to prefill the form fields, by assigning a value to
each input field’s 'value' attribute.
Figure 6-2 illustrates one such Web form, prefilled with data read from the
configuration file.
Users are, of course, free to resubmit the form with new data; as explained previously,
this submission will then be used to rewrite the configuration file with new values.
Figure 6-2 A Web form prefilled with data from a configuration file
Processing Directories
PHP also allows developers to work with directories on the file system, iterating through
directory contents or moving forward and backward through directory trees. Iterating through
a directory is a simple matter of calling PHP’s DirectoryIterator object, as in the following
example, which uses the DirectoryIterator to read a directory and list each file within it:
<?php
// initialize iterator with name of
// directory to process
$dit = new DirectoryIterator('.');
// loop over directory
// print names of files found
while($dit->valid()) {
if (!$dit->isDot()) {
echo $dit->getFilename() . "n";
}
$dit->next();
}
unset($dit);
?>
Here, a DirectoryIterator object is initialized with a directory name, and the object’s
rewind() method is used to reset the internal pointer to the first entry in the directory. A
while loop, which runs so long as a valid() entry exists, can then be used to iterate over
the directory. Individual filenames are retrieved with the getFilename() method, while
the isDot() method can be used to filter out the entries for the current (.) and parent (..)
directories. The next() method moves the internal pointer forward to the next entry.
You can also accomplish the same task with a while loop and some of PHP’s
directory manipulation functions . . . as in the following listing:
<?php
// create directory pointer
$dp = opendir('.') or die ('ERROR: Cannot open directory');
// read directory contents
// print filenames found
while ($file = readdir($dp)) {
if ($file != '.' && $file != '..') {
echo "$file n";
}
}
// destroy directory pointer
closedir($dp);
?>
Here, the opendir() function returns a pointer to the directory named in the function
call. This pointer is then used by the readdir() function to iterate over the directory,
returning a single entry each time it is invoked. It’s then easy to filter out the . and ..
directories, and print the names of the remaining entries. Once done, the closedir()
function closes the file pointer.
TIP
Also consider PHP’s scandir() function, which accepts a directory name and returns
an array containing a list of the files within that directory together with their sizes. It’s
then easy to process this array with a foreach loop.
In some cases, you might need to process not just the first-level directory, but also
its subdirectories and sub-subdirectories. A recursive function, which you learned about
in Chapter 5, is usually the best tool for this purpose: consider the next listing, which
illustrates one such function in action:
<?php
// function definition
// print names of files in a directory
// and its child directories
function printDir($dir, $depthStr='+') {
if (file_exists($dir)) {
// create directory pointer
$dp = opendir($dir) or die ('ERROR: Cannot open directory');
// read directory contents
// print names of files found
// call itself recursively if directories found
while ($file = readdir($dp)) {
if ($file != '.' && $file != '..') {
echo "$depthStr $dir/$file n";
if (is_dir("$dir/$file")) {
printDir("$dir/$file", $depthStr.'+');
}
}
}
// close directory pointer
closedir($dp);
}
}
// print contents of directory
// and all children
if (file_exists('.')) {
echo '<pre>';
printDir('.');
echo '<pre>';
}
?>
The printDir() function in this listing might appear complex, but it’s actually quite
simple. It accepts two arguments: the name of the top-level directory to use, and a “depth
string,” which indicates, via indentation, the position of a particular file or directory in the
hierarchy. Using this input, the function opens a pointer to the named directory and begins
processing it with readdir(), printing the name of each directory or file found. In the
event that a directory is found, the depth string is incremented by an additional character
and the printDir() function is itself recursively called to process that subdirectory. This
process continues until no further files or directories remain to be processed.
Figure 6-3 has an example of the output of this listing.
Figure 6-3 An indented directory listing
Performing Other File and Directory Operations
In addition to the tools you’ve seen in previous sections, PHP comes with a whole range
of file and directory manipulation functions, which allow you to check file attributes;
copy, move, and delete files; and work with file paths and extensions. Table 6-1 lists some
of the important functions in this category.
Checking if a File or Directory Exists
If you try reading or appending to a file that doesn’t exist, PHP will typically generate a
fatal error. Ditto for attempts to access or read/write from/to a directory that doesn’t exist.
To avoid these error messages, always check that the file or directory you’re attempting to
access already exists, with PHP’s file_exists() function. The next listing illustrates it
in action:
Function What It Does
file_exists() Tests if a file or directory exists
filesize() Returns the size of a file in bytes
realpath() Returns the absolute path of a file
pathinfo() Returns an array of information about a file and its path
stat() Provides information on file attributes and permissions
is_readable() Tests if a file is readable
is_writable() Tests if a file is writable
is_executable() Tests if a file is executable
is_dir() Tests if a directory entry is a directory
is_file() Tests if a directory entry is a file
copy() Copies a file
rename() Renames a file
unlink() Deletes a file
mkdir() Creates a new directory
rmdir() Removes a directory
include() / require() Reads an external file into the current PHP script
Table 6-1 Common PHP File and Directory Functions
<?php
// check file
if (file_exists('somefile.txt')) {
$str = file_get_contents('somefile.txt');
} else {
echo 'Named file does not exist. ';
}
// check directory
if (file_exists('somedir')) {
$files = scandir('somedir');
} else {
echo 'Named directory does not exist.';
}
?>
Calculating File Size
To calculate the size of a file in bytes, call the filesize() function with the filename
as argument:
<?php
// get file size
// output: 'File is 1327 bytes.'
if (file_exists('example.txt')) {
echo 'File is ' . filesize('example.txt') . ' bytes.';
} else {
echo 'Named file does not exist. ';
}
?>
Finding the Absolute File Path
To retrieve the absolute file system path to a file, use the realpath() function, as in the
next listing:
<?php
// get file path
// output: 'File path: /usr/local/apache/htdocs/
// /php-book/ch06/listings/example.txt'
if (file_exists('example.txt')) {
echo 'File path: ' . realpath('example.txt');
} else {
echo 'Named file does not exist. ';
}
?>
Q: Are PHP’s file functions case-sensitive with respect to filenames?
A: It depends on the underlying file system. Windows is case-insensitive with respect
to filenames, so PHP’s file functions are case-insensitive too. However, filenames
on *NIX systems are case-sensitive, and so PHP’s file functions are case-sensitive
too on these systems. Thus, given the file eXAMple.txt, the statement <?php file_
exists('example.txt'); ?> might return false on a *NIX system but true on a
Windows system.
You can also use the pathinfo() function, which returns an array containing the
file’s path, name, and extension. Here’s an example:
<?php
// get file path info as array
if (file_exists('example.txt')) {
print_r(pathinfo('example.txt'));
} else {
echo 'Named file does not exist. ';
}
?>
Retrieving File Attributes
You can obtain detailed information on a particular file, including its ownership,
permissions, and modification and access times, with PHP’s stat() function, which
returns this information as an associative array. Here’s an example:
<?php
// get file information
if (file_exists('example.txt')) {
print_r(stat('example.txt'));
} else {
echo 'Named file does not exist. ';
}
?>
You can check if a file is readable, writable or executable with the is_readable(),
is_writable(), and is_executable() functions. The following example illustrates
their usage:
<?php
// get file information
// output: 'File is: readable writable'
if (file_exists('example.txt')) {
echo 'File is: ';
// check for readable bit
if (is_readable('example.txt')) {
echo ' readable ';
}
// check for writable bit
if (is_writable('example.txt')) {
echo ' writable ';
}
// check for executable bit
if (is_executable('example.txt')) {
echo ' executable ';
}
} else {
echo 'Named file does not exist. ';
}
?>
The is_dir() function returns true if the argument passed to it is a directory, while
the is_file() function returns true if the argument passed to it is a file. Here’s an
example:
<?php
// test if file or directory
if (file_exists('example.txt')) {
if (is_file('example.txt')) {
echo 'It's a file.';
}
if (is_dir('example.txt')) {
echo 'It's a directory.';
}
} else {
echo 'ERROR: File does not exist.';
}
?>
Creating Directories
To create a new, empty directory, call the mkdir() function with the path and name of the
directory to be created:
<?php
if (!file_exists('mydir')) {
if (mkdir('mydir')) {
echo 'Directory successfully created.';
} else {
echo 'ERROR: Directory could not be created.';
}
} else {
echo 'ERROR: Directory already exists.';
}
?>
Copying Files
You can copy a file from one location to another by calling PHP’s copy() function with
the file’s source and destination paths as arguments. Here’s an example:
<?php
// copy file
if (file_exists('example.txt')) {
if (copy('example.txt', 'example.new.txt')) {
echo 'File successfully copied.';
} else {
echo 'ERROR: File could not be copied.';
}
} else {
echo 'ERROR: File does not exist.';
}
?>
It’s important to note that if the destination file already exists, the copy() function
will overwrite it.
Renaming Files or Directories
To rename or move a file (or directory), call PHP’s rename() function with the old and
new path names as arguments. Here’s an example that renames a file and a directory,
moving the file to a different location in the process:
<?php
// rename/move file
if (file_exists('example.txt')) {
if (rename('example.txt', '../example.new.txt')) {
echo 'File successfully renamed.';
} else {
echo 'ERROR: File could not be renamed.';
}
} else {
echo 'ERROR: File does not exist.';
}
// rename directory
if (file_exists('mydir')) {
if (rename('mydir', 'myotherdir')) {
echo 'Directory successfully renamed.';
} else {
echo 'ERROR: Directory could not be renamed.';
}
} else {
echo 'ERROR: Directory does not exist.';
}
?>
As with copy(), if the destination file already exists, the rename() function will
overwrite it.
CAUTION
PHP will only allow you to copy, delete, rename, create, and otherwise manipulate a file
or directory if the user "owning" the PHP script has the privileges necessary to perform
the task.
Removing Files or Directories
To remove a file, pass the filename and path to PHP’s unlink() function, as in the
following example:
<?php
// delete file
if (file_exists('dummy.txt')) {
if (unlink('dummy.txt')) {
echo 'File successfully removed.';
} else {
echo 'ERROR: File could not be removed.';
}
} else {
echo 'ERROR: File does not exist.';
}
?>
To remove an empty directory, PHP offers the rmdir() function, which does the
reverse of the mkdir() function. If the directory isn’t empty, though, it’s necessary to
first remove all its contents (including all subdirectories) and only then call the rmdir()
function to remove the directory. You can do this manually, but a recursive function is
usually more efficient—here’s an example, which demonstrates how to remove a directory
and all its children:
<?php
// function definition
// remove all files in a directory
function removeDir($dir) {
if (file_exists($dir)) {
// create directory pointer
$dp = opendir($dir) or die ('ERROR: Cannot open directory');
// read directory contents
// delete files found
// call itself recursively if directories found
while ($file = readdir($dp)) {
if ($file != '.' && $file != '..') {
if (is_file("$dir/$file")) {
unlink("$dir/$file");
} else if (is_dir("$dir/$file")) {
removeDir("$dir/$file");
}
}
}
// close directory pointer
// remove now-empty directory
closedir($dp);
if (rmdir($dir)) {
return true;
} else {
return false;
}
}
}
// delete directory and all children
if (file_exists('mydir')) {
if (removeDir('mydir')) {
echo 'Directory successfully removed.';
} else {
echo 'ERROR: Directory could not be removed.';
}
} else {
echo 'ERROR: Directory does not exist.';
}
?>
Here, the removeDir() function is a recursive function that accepts one input
argument: the name of the top-level directory to remove. The function begins by creating
a pointer to the directory with opendir() and then iterating over the directory’s contents
with a while loop—you’ve seen this technique in a previous section of this chapter.
For each directory entry found, the is_file() and is_dir() methods are used to
determine if the entry is a file or a sub-directory; if the former, the unlink() function is
used to delete the file and if the latter, the removeDir() function is called recursively
to again process the subdirectory’s contents. This process continues until no files or
subdirectories are left; at this point, the top-level directory is empty and can be removed
with a quick rmdir().
Reading and Evaluating External Files
To read and evaluate external files from within your PHP script, use PHP’s include()
or require() function. A very common application of these functions is to include a
standard header, footer, or copyright notice across all the pages of a Web site. Here’s an
example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
</head>
<body>
<?php require('header.php'); ?>
<p/>
This is the page body.
<p/>
<?php include('footer.php'); ?>
</body>
</html>
Here, the script reads two external files, header.php and footer.php, and places
the contents of these files at the location of the include() or require() call. It’s
important to note that any PHP code to be evaluated within the files included in this
manner must be enclosed within <?php ... ?> tags.
Q: What is the difference between include() and require()?
A: Fairly simple: a missing include() will generate a warning but allow script execution to continue,
whereas a missing require() will generate a fatal error that halts script execution.

More Related Content

What's hot (19)

PPT
File handling in c
Vikash Dhal
 
PPT
file
teach4uin
 
PPT
File in c
Prabhu Govind
 
PPT
File handling-c
CGC Technical campus,Mohali
 
PPT
File in C Programming
Sonya Akter Rupa
 
PDF
Module 03 File Handling in C
Tushar B Kute
 
PPT
File handling in 'C'
Gaurav Garg
 
PPT
File handling in c
David Livingston J
 
PPTX
File Management in C
Paurav Shah
 
PPSX
C programming file handling
argusacademy
 
PPTX
File handling in C
Kamal Acharya
 
PPTX
File handling in c
mohit biswal
 
PPT
File handling in c
thirumalaikumar3
 
PPT
File handling-c programming language
thirumalaikumar3
 
PPT
File Management
Ravinder Kamboj
 
PPTX
File handling in C
Rabin BK
 
PPTX
Files
sana mateen
 
File handling in c
Vikash Dhal
 
file
teach4uin
 
File in c
Prabhu Govind
 
File in C Programming
Sonya Akter Rupa
 
Module 03 File Handling in C
Tushar B Kute
 
File handling in 'C'
Gaurav Garg
 
File handling in c
David Livingston J
 
File Management in C
Paurav Shah
 
C programming file handling
argusacademy
 
File handling in C
Kamal Acharya
 
File handling in c
mohit biswal
 
File handling in c
thirumalaikumar3
 
File handling-c programming language
thirumalaikumar3
 
File Management
Ravinder Kamboj
 
File handling in C
Rabin BK
 

Similar to Php files (20)

PPSX
DIWE - File handling with PHP
Rasan Samarasinghe
 
PPTX
PHP File Handling
Degu8
 
PDF
FILES IN C
yndaravind
 
DOCX
Files nts
kalyani66
 
PDF
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
PPTX
Programming C- File Handling , File Operation
svkarthik86
 
PPTX
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
PPTX
lecture 10.pptx
ITNet
 
PPTX
Chap 5 php files part 1
monikadeshmane
 
PPTX
File Handling in C
VrushaliSolanke
 
PPTX
File Handling ppt.pptx shjd dbkd z bdjdb d
ssusere1e8b7
 
PPTX
Unit-VI.pptx
Mehul Desai
 
PPTX
C Programming Unit-5
Vikram Nandini
 
PPT
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
DOCX
Unit 8
Keerthi Mutyala
 
PPT
Unit5
mrecedu
 
PPTX
File management
lalithambiga kamaraj
 
PPTX
File in C language
Manash Kumar Mondal
 
PPTX
pspp-rsk.pptx
ARYAN552812
 
PPTX
PPS PPT 2.pptx
Sandeepbhuma1
 
DIWE - File handling with PHP
Rasan Samarasinghe
 
PHP File Handling
Degu8
 
FILES IN C
yndaravind
 
Files nts
kalyani66
 
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
Programming C- File Handling , File Operation
svkarthik86
 
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
lecture 10.pptx
ITNet
 
Chap 5 php files part 1
monikadeshmane
 
File Handling in C
VrushaliSolanke
 
File Handling ppt.pptx shjd dbkd z bdjdb d
ssusere1e8b7
 
Unit-VI.pptx
Mehul Desai
 
C Programming Unit-5
Vikram Nandini
 
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
Unit5
mrecedu
 
File management
lalithambiga kamaraj
 
File in C language
Manash Kumar Mondal
 
pspp-rsk.pptx
ARYAN552812
 
PPS PPT 2.pptx
Sandeepbhuma1
 
Ad

Recently uploaded (20)

PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Dimensions of Societal Planning in Commonism
StefanMz
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Horarios de distribución de agua en julio
pegazohn1978
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Ad

Php files

  • 1. Files: Opening and Closing Files The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate. Files modes can be specified as one of the six options in this table. Mode Purpose r Opens the file for reading only. Places the file pointer at the beginning of the file. r+ Opens the file for reading and writing. Places the file pointer at the beginning of the file. w Opens the file for writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attempts to create a file. w+ Opens the file for reading and writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attempts to create a file. a Opens the file for writing only. Places the file pointer at the end of the file. If files does not exist then it attempts to create a file. a+ Opens the file for reading and writing only. Places the file pointer at the end of the file. If files does not exist then it attempts to create a file. If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file. After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails. Check End-of-file The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length.
  • 2. Note: You cannot read from files opened in w, a, and x mode! if (feof($file)) echo "End of file"; Reading a File Line by Line The fgets() function is used to read a single line from a file. Note: After a call to this function the file pointer has moved to the next line. Example The example below reads a file line by line, until the end of file is reached: <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br>"; } fclose($file); ?> Reading a File Character by Character The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character. Example The example below reads a file character by character, until the end of file is reached: <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?> Reading a file
  • 3. Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes. The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes. So here are the steps required to read a file with PHP. Open a file using fopen() function. Get the file's length using filesize() function. Read the file's content using fread() function. Close the file with fclose() function. The following example assigns the content of a text file to a variable then displays those contents on the web page. <html> <head> <title>Reading a file using PHP</title> </head> <body> <?php $filename = "/home/user/guest/tmp.txt"; $file = fopen( $filename, "r" ); if( $file == false ) { echo ( "Error in opening file" ); exit(); } $filesize = filesize( $filename ); $filetext = fread( $file, $filesize ); fclose( $file ); echo ( "File size : $filesize bytes" ); echo ( "<pre>$filetext</pre>" ); ?> </body> </html> Writing a file A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.
  • 4. The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument <?php $filename = "/home/user/guest/newfile.txt"; $file = fopen( $filename, "w" ); if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple testn" ); fclose( $file ); ?> <html> <head> <title>Writing a file using PHP</title> </head> <body> <?php if( file_exist( $filename ) ) { $filesize = filesize( $filename ); $msg = "File created with name $filename "; $msg .= "containing $filesize bytes"; echo ($msg ); } else { echo ("File $filename does not exit" ); } ?> </body> </html> The filesystem functions are used to access and manipulate the filesystem PHP provides you all the posible functions you may need to manipulate a file. Installation: The error and logging functions are part of the PHP core. There is no installation needed to use these functions. Runtime Configuration:
  • 5. The behaviour of these functions is affected by settings in php.ini. Name Default Changeable Changelog allow_url_fopen "1" PHP_INI_ALL PHP_INI_ALL in PHP <= 4.3.4. PHP_INI_SYSTEM in PHP < 6. Available since PHP 4.0.4. allow_url_include "0" PHP_INI_ALL PHP_INI_SYSTEM in PHP 5. Available since PHP 5.2.0. user_agent NULL PHP_INI_ALL Available since PHP 4.0.3. default_socket_timeout "60" PHP_INI_ALL Available since PHP 4.3.0. from "" PHP_INI_ALL auto_detect_line_endings "0" PHP_INI_ALL Available since PHP 4.3.0. PHP Error and Logging Constants: PHP: indicates the earliest version of PHP that supports the constant. You can use any of the constant while configuring your php.ini file. Constant Description PHP GLOB_BRACE GLOB_ONLYDIR GLOB_MARK GLOB_NOSORT GLOB_NOCHECK GLOB_NOESCAPE PATHINFO_DIRNAME PATHINFO_BASENAME PATHINFO_EXTENSION PATHINFO_FILENAME 5.2.0 FILE_USE_INCLUDE_PATH Search for filename in include_path 5.0.0
  • 6. FILE_APPEND Append content to existing file. FILE_IGNORE_NEW_LINES Strip EOL characters 5.0.0 FILE_SKIP_EMPTY_LINES Skip empty lines 5.0.0 FILE_BINARY Binary mode 6.0.0 FILE_TEXT Text mode 6.0.0 List of Functions PHP: indicates the earliest version of PHP that supports the function. Function Description PHP basename() Returns filename component of path 3 chgrp() Changes file group 3 chmod() Changes file mode 3 chown() Changes file owner 3 clearstatcache() Clears file status cache 3 copy() Copies file 3 delete() Deletes file dirname() Returns directory name component of path 3 disk_free_space() Returns available space in directory 4.0.7 disk_total_space() Returns the total size of a directory 4.0.7 diskfreespace() Alias of disk_free_space() 4.0.7 fclose() Closes an open file pointer 3 feof() Tests for end-of-file on a file pointer 3 fflush() Flushes the output to a file 4 fgetc() Gets character from file pointer 3 fgetcsv() Gets line from file pointer and parse for CSV fields 3 fgets() Gets line from file pointer 3
  • 7. fgetss() Gets line from file pointer and strip HTML tags 3 file_exists() Checks whether a file or directory exists 3 file_get_contents() Reads entire file into a string 4.3.0 file_put_contents() Write a string to a file 5 file() Reads entire file into an array 3 fileatime() Gets last access time of file 3 filectime() Gets inode change time of file 3 filegroup() Gets file group 3 fileinode() Gets file inode 3 filemtime() Gets file modification time 3 fileowner() Gets file owner 3 fileperms() Gets file permissions 3 filesize() Gets file size 3 filetype() Gets file type 3 flock() Portable advisory file locking 3 fnmatch() Match filename against a pattern 4.0.3 fopen() Opens file or URL 3 fpassthru() Output all remaining data on a file pointer 3 fputcsv() Format line as CSV and write to file pointer 5.1.0 fputs() Alias of fwrite() 3 fread() Binary-safe file read 3 fscanf() Parses input from a file according to a format 4.0.1 fseek() Seeks on a file pointer 3 fstat() Gets information about a file using an open file pointer 4 ftell() Tells file pointer read/write position 3 ftruncate() Truncates a file to a given length 4
  • 8. fwrite() Binary-safe file write 3 glob() Find pathnames matching a pattern 4.0.3 is_dir() Tells whether the filename is a directory 3 is_executable() Tells whether the filename is executable 3 is_file() Tells whether the filename is a regular file 3 is_link() Tells whether the filename is a symbolic link 3 is_readable() Tells whether the filename is readable 3 is_uploaded_file() Tells whether the file was uploaded via HTTP POST 4.0.3 is_writable() Tells whether the filename is writable 3 is_writeable() Alias of is_writable() 3 lchgrp() Changes group ownership of symlink 5.1.2 lchown() Changes user ownership of symlink 5.1.2 link() Create a hard link 3 linkinfo() Gets information about a link 3 lstat() Gives information about a file or symbolic link 3 mkdir() Makes directory 3 move_uploaded_file() Moves an uploaded file to a new location 4.0.3 parse_ini_file() Parse a configuration file 4 pathinfo() Returns information about a file path 4.0.3 pclose() Closes process file pointer 3 popen() Opens process file pointer 3 readfile() Outputs a file 3 readlink() Returns the target of a symbolic link 3 realpath() Returns canonicalized absolute pathname 4 rename() Renames a file or directory 3 rewind() Rewind the position of a file pointer 3
  • 9. rmdir() Removes directory 3 set_file_buffer() Alias of stream_set_write_buffer() 3 stat() Gives information about a file 3 symlink() Creates a symbolic link 3 tempnam() Create file with unique file name 3 tmpfile() Creates a temporary file 3 touch() Sets access and modification time of file 3 umask() Changes the current umask 3 unlink() Deletes a file 3 List of All File functions in php Introduction If you were having trouble in remembering all file related functions of PHP, then don't worry, I'm publishing here a full list of all of them, so that you can easily use any of them. File system related functions were divided into 9 extensions of php whose names are shown below. List of File system related extensions Click on links to directly Jump on page section. 1. Direct IO, 2. Directories, 3. Fileinfo, 4. Filesystem, 5. Inotify, 6. Mimetype (No functions found), 7. Proctile, 8. Xattr, 9. And xdiff. Filesystem functions in php Function Name Description Syntax Other information
  • 10. Function Name Description Syntax Other information basename Given a string containing the path to a file or directory, this function will return the trailing name component. basename ( string $path [, string $suffix ] ) chgrp Changes file group chgrp ( string $filename , mixed $group ) group - A group name or number. chmod Attempts to change the mode of the specified file to that given in $mode. chmod ( string $filename , int $mode ) Returns TRUE on success or FALSE on failure. chown Attempts to change the owner of the file $filename to $user user. Only the superuser may change the owner of a file. chown ( string $filename , mixed $user ) filename - path to the file, user - A user name or number. clearstatcache Clears file status cache clearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] ) clear_realpath_cache - Whether to clear the realpath cache or not. copy Makes a copy of the file $source to $dest. copy ( string $source , string $dest [, resource $context ] ) Returns TRUE on success or FALSE on failure. delete This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place. delete ( void ) dirname Given a string containing the path of a file or directory, this function will return the parent directory's path. dirname ( string $path ) disk_free_space Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition. disk_free_space ( string $directory )
  • 11. Function Name Description Syntax Other information disk_total_space Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition. disk_total_space ( string $directory ) Returns the total number of bytes as a float or FALSE on failure. diskfreespace This function is an alias of: disk_free_space(). fclose The file pointed to by handle is closed. fclose ( resource $handle ) handle - The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen(). feof Tests for end-of-file on a file pointer. feof ( resource $handle ) The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). fflush This function forces a write of all buffered output to the resource pointed to by the file handle. fflush ( resource $handle ) Returns TRUE on success or FALSE on failure. fgetc Gets a character from the given file pointer. fgetc ( resource $handle ) Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF. fgetcsv Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '' ]]]] ) handle - A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen(). fgets Gets a line from file pointer. fgets ( resource $handle [, int $length ] ) length - If no length is specified, it will keep reading from the stream
  • 12. Function Name Description Syntax Other information until it reaches the end of the line. fgetss Identical to fgets(), except that fgetss() attempts to strip any NUL bytes, HTML and PHP tags from the text it reads. fgetss ( resource $handle [, int $length [, string $allowable_tags ]] ) allowable_tags - You can use the optional third parameter to specify tags which should not be stripped. file_exists Checks whether a file or directory exists. file_exists ( string $filename ) file_get_contents Reads entire file into a string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] ) file_put_contents This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) file Reads an entire file into an array. file ( string $filename [, int $flags = 0 [, resource $context ]] ) fileatime Gets the last access time of the given file. fileatime ( string $filename ) filectime Gets the inode change time of a file. filectime ( string $filename ) filegroup Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. filegroup ( string $filename ) fileinode Gets the file inode. fileinode ( string $filename ) Returns the inode number of the file, or FALSE on failure.
  • 13. Function Name Description Syntax Other information filemtime This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed. filemtime ( string $filename ) Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function. fileowner Gets the file owner. fileowner ( string $filename ) Returns the user ID of the owner of the file, or FALSE on failure. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username. fileperms Gets permissions for the given file. fileperms ( string $filename ) Returns the permissions on the file, or FALSE on failure. filesize Gets the size for the given file.filesize ( string $filename ) filetype Returns the type of the given file. filetype ( string $filename ) Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown. flock Portable advisory file locking flock ( resource $handle , int $operation [, int &$wouldblock ] ) fnmatch Match filename against a pattern fnmatch ( string $pattern , string $string [, int $flags = 0 ] ) fopen Opens file or URL fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] ) fpassthru Output all remaining data on a file pointer fpassthru ( resource $handle )
  • 14. Function Name Description Syntax Other information fputcsv Format line as CSV and write to file pointer fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] ) fputs This function is an alias of: fwrite(). fread Binary-safe file read fread ( resource $handle , int $length ) fscanf Parses input from a file according to a format fscanf ( resource $handle , string $format [, mixed &$... ] ) fseek Seeks on a file pointer fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] ) fstat Gets information about a file using an open file pointer fstat ( resource $handle ) handle - A file system pointer resource that is typically created using fopen(). ftell Returns the position of the file pointer referenced by handle. ftell ( resource $handle ) ftruncate Truncates a file to a given length ftruncate ( resource $handle , int $size ) fwrite Binary-safe file write fwrite ( resource $handle , string $string [, int $length ] ) glob Find pathnames matching a pattern glob ( string $pattern [, int $flags = 0 ] ) is_dir Tells whether the given filename is a directory. is_dir ( string $filename ) is_executable Tells whether the filename is executable. is_executable ( string $filename )
  • 15. Function Name Description Syntax Other information is_file Tells whether the given file is a regular file. is_file ( string $filename ) is_link Tells whether the given file is a symbolic link. is_link ( string $filename ) is_readable Tells whether a file exists and is readable. is_readable ( string $filename ) is_uploaded_file Tells whether the file was uploaded via HTTP POST is_uploaded_file ( string $filename ) is_writable Tells whether the filename is writable is_writable ( string $filename ) is_writeable This function is an alias of: is_writable(). lchgrp Changes group ownership of symlink lchgrp ( string $filename , mixed $group ) lchown Changes user ownership of symlink lchown ( string $filename , mixed $user ) link link() creates a hard link. link ( string $target , string $link ) linkinfo Gets information about a link linkinfo ( string $path ) lstat Gives information about a file or symbolic link lstat ( string $filename ) mkdir Attempts to create the directory specified by pathname. mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] ) move_uploaded_file Moves an uploaded file to a new location move_uploaded_file ( string $filename , string $destination ) parse_ini_file Parse a configuration file parse_ini_file ( string $filename [, bool $process_sections = false
  • 16. Function Name Description Syntax Other information [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) parse_ini_string Parse a configuration string parse_ini_string ( string $ini [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) pathinfo pathinfo() returns an associative array containing information about path. pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] ) pclose Closes a file pointer to a pipe opened by popen(). pclose ( resource $handle ) Returns the termination status of the process that was run. In case of an error then -1 is returned. popen Opens process file pointer popen ( string $command , string $mode ) readfile Outputs a file readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] ) readlink Returns the target of a symbolic link readlink ( string $path ) realpath_cache_get Get the contents of the realpath cache. realpath_cache_get ( void ) Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the
  • 17. Function Name Description Syntax Other information cache. realpath_cache_size Get the amount of memory used by the realpath cache. realpath_cache_size ( void ) realpath Returns canonicalized absolute pathname realpath ( string $path ) rename Attempts to rename oldname to newname. rename ( string $oldname , string $newname [, resource $context ] ) rewind Sets the file position indicator for handle to the beginning of the file stream. rewind ( resource $handle ) rmdir Removes directory rmdir ( string $dirname [, resource $context ] ) set_file_buffer This function is an alias of: stream_set_write_buffer(). stat Gives information about a file stat ( string $filename ) symlink Creates a symbolic link symlink ( string $target , string $link ) tempnam Create file with unique file name tempnam ( string $dir , string $prefix ) Returns the new temporary filename, or FALSE on failure. tmpfile Creates a temporary fileCreates a temporary file with a unique name in read- write (w+) mode and returns a file handle . tmpfile ( void ) touch Sets access and modification time of file touch ( string $filename [, int $time = time() [, int $atime ]] ) umask Changes the current umask umask ([ int $mask ] ) unlink Deletes a file unlink ( string $filename [, Returns TRUE on success
  • 18. Function Name Description Syntax Other information resource $context ] ) or FALSE on failure. Direct IO functions in php Function Name Description Syntax Other Information dio_close Closes the file description given by fd dio_close(resource $fd) fd - The file descriptor returned by dio_open() dio_fcntl The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied. dio_fcntl ( resource $fd , int $cmd [, mixed $args ] ) cmd - can be F_SETLK, F_SETLKW, F_GETLK, F_DUPFD, F_SETFL dio_open dio_open() opens a file and returns a new file descriptor for it. dio_open ( string $filename , int $flags [, int $mode = 0 ] ) filename - Path of the file to open. dio_read The function dio_read() reads and returns len bytes from file with descriptor fd. string dio_read ( resource $fd [, int $len = 1024 ] ) len - Number of Bytes to read. dio_seek The function dio_seek() is used to change the file position of the given file descriptor. dio_seek ( resource $fd , int $pos [, int $whence = SEEK_SET ] ) pos - The new position, Whence -Specifies how the position pos should be interpreted. dio_stat dio_stat() returns information about the given file descriptor. dio_stat ( resource $fd ) fd - The file descriptor returned by dio_open(). dio_tcsetattr dio_tcsetattr() sets the terminal attributes and baud rate of the open fd. dio_tcsetattr ( resource $fd , array $options ) Currently available options are 'baud' , 'bits', 'stop', 'parity'. dio_truncate dio_truncate() truncates a file to at most offset bytes in size. The offset in bytes. Returns TRUE on success or FALSE on failure. dio_write dio_write() writes up to len bytes from data to file fd. int dio_write ( resource $fd , string $data [, int $len = 0 ] ) data - The written data.
  • 19. Directory functions in PHP Function Name Description Syntax Other Information chdir Changes PHP's current directory to new directory. chdir ( string $directory ) directory - The new current directory chroot Changes the root directory of the current process to directory, and changes the current working directory to "/". chroot ( string $directory ) directory - The path to change the root directory to. dir Return an instance of the Directory class - object-oriented mechanism (search google) closedir Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir(). closedir ([ resource $dir_handle ] ) dir_handle - The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed. getcwd Gets the current working directory. getcwd ( ) Returns the current working directory on success, or FALSE on failure. opendir Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls. opendir ( string $path [, resource $context ] ) path - The directory path that is to be opened readdir Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem. readdir ([ resource $dir_handle ] ) Returns the filename on success or FALSE on failure. rewinddir Resets the directory stream indicated by dir_handle to the beginning of the directory. rewinddir ([ resource $dir_handle ] ) scandir Returns an array of files and directories from the directory. scandir ( string $directory [, int $sorting_order = 0 [, sorting_order - By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is
  • 20. Function Name Description Syntax Other Information resource $context ]] ) set to non-zero, then the sort order is alphabetical in descending order. Fileinfo functions in PHP Function Name Description Syntax Other Information finfo_buffer This function is used to get information about binary data in a string. finfo_buffer ( resource $finfo , string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] ) finfo - Fileinfo resource returned by finfo_open(), $string - Content of a file to be checked, finfo_close This function closes the resource opened by finfo_open(). finfo_close ( resource $finfo ) finfo - Fileinfo resource returned by finfo_open(). finfo_file This function is used to get information about a file. finfo_file ( resource $finfo , string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] ) file_name - Name of a file to be checked. finfo_open This function opens a magic database and returns its resource. finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] ) Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the MAGIC environment variable is used. If this variable is not set either, /usr/share/misc/magic is used by default. A .mime and/or .mgc suffix is added if needed. finfo_set_flags This function sets various Fileinfo options. Options can be set also directly in finfo_set_flags ( resource $finfo , int $options ) Returns TRUE on success or FALSE on failure.
  • 21. Function Name Description Syntax Other Information finfo_open() or other Fileinfo functions. mime_content_type Returns the MIME content type for a file as determined by using information from the magic.mime file. mime_content_type ( string $filename ) filename - Path to the tested file. Inotify functions in PHP Function Name Description Syntax Other Information inotify_add_watch inotify_add_watch() adds a new watch or modify an existing watch for the file or directory specified in pathname. inotify_add_watch ( resource $inotify_instance , string $pathname , int $mask ) inotify_instance - Resource returned by inotify_init() inotify_init Initialize an inotify instance for use with inotify_add_watch() inotify_init ( void ) inotify_queue_len This function allows to know if inotify_read() will block or not. If a number upper than zero is returned, there are pending events and inotify_read() will not block. inotify_queue_len ( resource $inotify_instance ) inotify_read Read inotify events from an inotify instance. inotify_read ( resource $inotify_instance ) inotify_rm_watch Remove an existing watch from an inotify instance inotify_rm_watch ( resource $inotify_instance , int $watch_descriptor ) watch_descriptor - Watch to remove from the instance Proctile functions in PHP
  • 22. Function Name Description Syntax Other Information setproctitle Sets the process title of the current process. setproctitle ( string $title ) title - The title to use as the process title. setthreadtitle Sets the thread title. setthreadtitle ( string $title ) Returns TRUE on success or FALSE on failure. xattr functions of php Function Name Description Syntax Other Information xattr_get This function gets the value of an extended attribute of a file. xattr_get ( string $filename , string $name [, int $flags = 0 ] ) filename - The file from which we get the attribute, name - The name of the attribute. xattr_list This functions gets a list of names of extended attributes of a file. xattr_list ( string $filename [, int $flags = 0 ] ) filename - The path of the file. xattr_remove This function removes an extended attribute of a file. xattr_remove ( string $filename , string $name [, int $flags = 0 ] ) xattr_set This function sets the value of an extended attribute of a file. xattr_set ( string $filename , string $name , string $value [, int $flags = 0 ] ) value - The value of the attribute xattr_supported This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required. xattr_supported ( string $filename [, int $flags = 0 ] ) filename - The path of the tested file. xdiff functions in PHP Function Name Description Syntax Other Information xdiff_file_bdiff_size Returns a size of a result file that would xdiff_file_bdiff_size ( string file - The path to the binary patch created by
  • 23. Function Name Description Syntax Other Information be created after applying binary patch from file file to the original file. $file ) xdiff_string_bdiff() or xdiff_string_rabdiff() function. xdiff_file_bdiff Make binary diff of two files xdiff_file_bdiff ( string $old_file , string $new_file , string $dest ) dest - Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable. xdiff_file_bpatch Patch a file with a binary diff xdiff_file_bpatch ( string $file , string $patch , string $dest ) dest - Path of the resulting file, patch - The binary patch file. xdiff_file_diff_binary Alias of xdiff_file_bdiff xdiff_file_diff_binary ( string $old_file , string $new_file , string $dest ) xdiff_file_diff Make unified diff of two files xdiff_file_diff ( string $old_file , string $new_file , string $dest [, int $context = 3 [, bool $minimal = false ]] ) xdiff_file_merge3 Merge 3 files into one xdiff_file_merge3 ( string $old_file , string $new_file1 , string $new_file2 , string $dest ) dest - Path of the resulting file, containing merged changed from both new_file1 and new_file2. xdiff_file_patch_binary Alias of xdiff_file_bpatch xdiff_file_patch_binary ( string $file , string $patch , string $dest ) xdiff_file_patch Patch a file with an unified diff xdiff_file_patch ( string $file , string $patch , string $dest [, int $flags = DIFF_PATCH_NORMAL ] ) xdiff_file_rabdiff Make binary diff of two files using the xdiff_file_rabdiff ( string $old_file , string $new_file ,
  • 24. Function Name Description Syntax Other Information Rabin's polynomial fingerprinting algorithm string $dest ) xdiff_string_bdiff_size Returns a size of a result file that would be created after applying binary $patch to the original file. xdiff_string_bdiff_size ( string $patch ) patch - The binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function. xdiff_string_bdiff Make binary diff of two strings xdiff_string_bdiff ( string $old_data , string $new_data ) xdiff_string_bpatch Patch a string with a binary diff xdiff_string_bpatch ( string $str , string $patch ) xdiff_string_diff_binary Alias of xdiff_string_bdiff xdiff_string_bdiff ( string $old_data , string $new_data ) xdiff_string_diff Make unified diff of two strings xdiff_string_diff ( string $old_data , string $new_data [, int $context = 3 [, bool $minimal = false ]] ) xdiff_string_merge3 Merge 3 strings into one xdiff_string_merge3 ( string $old_data , string $new_data1 , string $new_data2 [, string &$error ] ) xdiff_string_patch_binary Alias of xdiff_string_bpatch xdiff_string_patch_binary ( string $str , string $patch ) xdiff_string_patch Patch a string with an unified diff xdiff_string_patch ( string $str , string $patch [, int $flags [, string &$error ]] ) xdiff_string_rabdiff Make binary diff of two strings using the Rabin's polynomial fingerprinting xdiff_string_bdiff ( string $old_data , string $new_data )
  • 25. Function Name Description Syntax Other Information algorithm John Donne famously said, “No man is an island,” and this maxim holds true for PHP scripts as well. So far, all the examples you’ve seen have been self-contained, with their source data arriving either from user input or from variables hard-wired into the program body. In reality, though, your PHP script will need to work with data retrieved from disk files, SQL resultsets, XML documents, and many other data sources. PHP comes with numerous built-in functions to access these data sources and this chapter will get you started on the road to discovering them, by focusing specifically on PHP’s file system functions. With 70+ functions available, there’s an abundance of options; this chapter will give you a crash course in the most important ones, with both examples and practical projects of reading, writing, and manipulating disk files and directories. Reading Files PHP’s file manipulation API is extremely flexible: it lets you read files into a string or into an array, from the local file system or a remote URL, by lines, bytes, or characters. The following sections explain all these variants in greater detail. Reading Local Files The easiest way to read the contents of a disk file in PHP is with the file_get_ contents() function. This function accepts the name and path to a disk file, and reads the entire file into a string variable in one fell swoop. Here’s an example: <?php // read file into string $str = file_get_contents('example.txt') or die('ERROR: Cannot find file'); echo $str; ?> An alternative method of reading data from a file is PHP’s file() function, which accepts the name and path to a file and reads the entire file into an array, with each element of the array representing one line of the file. To process the file, all you need do is iterate over the array using a foreach loop. Here’s an example, which reads a file into an array and then displays it using such a loop: <?php // read file into array $arr = file('example.txt') or die('ERROR: Cannot find file'); foreach ($arr as $line) { echo $line; } ?> Reading Remote Files Both file_get_contents() and file() also support reading data from URLs, using either the HTTP or FTP protocol. Here’s an example, which reads an HTML file off the Web into an array: <?php // read file into array $arr = file('http://www.google.com') or die('ERROR: Cannot find file'); foreach ($arr as $line) { echo $line;
  • 26. } ?> In case of slow network links, it’s sometimes more efficient to read a remote file in “chunks,” to maximize the efficiency of available network bandwidth. To do this, use the fgets() function to read a specific number of bytes from a file, as in the next example: <?php // read file into array (chunks) $str = '';$fp = fopen('http://www.google.com', 'r') or die('ERROR: Cannot open file'); while (!feof($fp)) { $str .= fgets($fp,512); } fclose($fp); echo $str; ?> This listing introduces four new functions, so let’s take a closer look at it. First, the fopen() function: it accepts the name of the source file and an argument indicating whether the file is to be opened in read ('r'), write ('w'), or append ('a') mode, and then creates a pointer to the file. Next, a while loop calls the fgets() function continuously in a loop to read a specific number of bytes from the file and append these bytes to a string variable; this loop continues until the feof() function returns true, indicating that the end of the file has been reached. Once the loop has completed, the fclose() function destroys the file pointer. NOTE In order to read remote URLs, the PHP configuration variable 'allow_url_fopen' must be set to true in the PHP configuration file php.ini. If this variable is set to false, all attempts to read remote files will fail. Reading Specific Segments of a File A final twist involves reading only a specific block of lines from a line—something that can be accomplished with a combination of PHP’s fseek() and fgets() functions. Consider the next example, which sets up a user-defined function named readBlock() and accepts three arguments: the filename, the starting line number, and the number of lines to return from the starting point: <?php // function definition // read a block of lines from a file function readBlock($file, $start=1, $lines=null) { // open file $fp = fopen($file, 'r') or die('ERROR: Cannot find file'); // initialize counters $linesScanned = 1; $linesRead = 0; $out = ''; // loop until end of file while (!feof($fp)) { // get each line $line = fgets($fp); // if start position is reached // append line to output variable if ($linesScanned >= $start) { $out .= $line; $linesRead++; // if max number of lines is defined and reached // break out of loop if (!is_null($linesRead) && $linesRead == ($lines)) { break; } }
  • 27. $linesScanned++; } return $out; } echo readBlock('example.txt', 3, 4); ?> Within readBlock(), a loop iterates through the file line by line, until the starting line number is reached (a line counter named $linesScanned keeps track of the current line number, incrementing by 1 on each iteration of the loop). Once the starting line is reached, it (and all subsequent lines) are read into a string variable until the specified maximum number of lines are processed or until the end of the file is reached. Writing Files The flip side of reading data from files is writing data to them. And PHP comes with a couple of different ways to do this as well. The first is the file_put_contents() function, a close cousin of the file_get_contents() function you read about in the preceding section: this function accepts a filename and path, together with the data to be written to the file, and then writes the latter to the former. Here’s an example: <?php // write string to file $data = "A fish n out of n watern"; file_put_contents('output.txt', $data) or die('ERROR: Cannot write file'); echo 'Data written to file'; ?> If the file specified in the call to file_put_contents() already exists on disk, file_put_contents() will overwrite it by default. If, instead, you’d prefer to preserve the file’s contents and simply append new data to it, add the special FILE_APPEND flag to your file_put_contents() function call as a third argument. Here’s an example: <?php // write string to file $data = "A fish n out of n watern"; file_put_contents('output.txt', $data, FILE_APPEND) or die('ERROR: Cannot write file'); echo 'Data written to file'; ?> An alternative way to write data to a file is to create a file pointer with fopen(), and then write data to the pointer using PHP’s fwrite() function. Here’s an example of this technique: <?php // open and lock file // write string to file // unlock and close file $data = "A fish n out of n watern"; $fp = fopen('output.txt', 'w') or die('ERROR: Cannot open file'); flock($fp, LOCK_EX) or die ('ERROR: Cannot lock file'); fwrite($fp, $data) or die ('ERROR: Cannot write file'); flock($fp, LOCK_UN) or die ('ERROR: Cannot unlock file'); fclose($fp); echo 'Data written to file'; ?> Notice the flock() function from the preceding listing: this function “locks” a file before reading or writing it, so that it cannot be accessed by another process. Doing this reduces the possibility of data corruption that might occur if two processes attempt to write different data to the same file at the same instant. The second parameter to flock()specifies the type of lock: LOCK_EX creates an exclusive lock for writing, LOCK_SH creates a non-exclusive lock for reading, and LOCK_UN destroys the lock.
  • 28. Q: Can I read and write binary files with PHP? A: Yes. The file_get_contents(), file_put_contents(), and file() functions all read and write data in binary format by default; this lets you use PHP with binary files without worrying that your data will get corrupted. NOTE The directory into which you’re trying to save the file must already exist, or else PHP will generate a fatal error. You can test if a directory exists with the file_exists()function. his 6 -1 Reading and Writing Configuration Files Now that you know how to read and write files, let’s try creating an application that uses the functions described in the preceding section. Assume for a second that you’re developing a Weblog application, and you’d like your users to be able to configure certain aspects of this application’s behavior—for example, how many posts appear on the index page or the e-mail address that comments are sent to. In this case, you’d probably need to build a Web-based form that allows users to input these configuration values and saves them to a file that your application can read as needed. This next listing generates just such a Web form, allowing users to enter values for different configuration values and then saving this information to a disk file. When users revisit the form, the data previously saved to the file is read and used to prefill the form’s fields. Here’s the code (configure.php): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Project 6-1: Reading And Writing Configuration Files</title> </head> <body> <h2>Project 6-1: Reading And Writing Configuration Files</h2> <?php // define configuration filename and path $configFile = 'config.ini'; // if form not yet submitted // display form if (!isset($_POST['submit'])) { // set up array with default parameters $data = array(); $data['AdminEmailAddress'] = null; $data['DefAuthor'] = null; $data['NumPosts'] = null; $data['NumComments'] = null; $data['NotifyURL'] = null; // read current configuration values // use them to pre-fill the form if (file_exists($configFile)) { $lines = file($configFile); foreach ($lines as $line) { $arr = explode('=', $line); $i = count($arr) - 1; (continued) $data[$arr[0]] = $arr[$i]; } } ?> <form method="post" action="configure.php"> Administrator email address: <br /> <input type="text" size="50" name="data[AdminEmailAddress]" value="<?php echo $data['AdminEmailAddress']; ?>"/> <p> Default author name: <br /> <input type="text" name="data[DefAuthor]" value="<?php echo $data['DefAuthor']; ?>"/> <p>
  • 29. Number of posts on index page: <br /> <input type="text" size="4" name="data[NumPosts]" value="<?php echo $data['NumPosts']; ?>"/> <p> Number of anonymous comments: <br /> <input type="text" size="4" name="data[NumComments]" value="<?php echo $data['NumComments']; ?>"/> <p> URL for automatic notification of new posts: <br /> <input type="text" size="50" name="data[NotifyURL]" value="<?php echo $data['NotifyURL']; ?>"/> <p> <input type="submit" name="submit" value="Submit" /> </form> <?php // if form submitted // process form input } else { // read submitted data $config = $_POST['data']; // validate submitted data as necessary if ((trim($config['NumPosts']) != '' && (int)$config['NumPosts'] <= 0) || (trim($config['NumComments']) != '' && (int)$config['NumComments'] <= 0)) { die('ERROR: Please enter a valid number'); } // open and lock configuration file for writing $fp = fopen($configFile, 'w+') or die('ERROR: Cannot open configuration file for writing'); flock($fp, LOCK_EX) or die('ERROR: Cannot lock configuration file for writing'); // write each configuration value to the file foreach ($config as $key => $value) { if (trim($value) != '') { fwrite($fp, "$key=$valuen") or die('ERROR: Cannot write [$key] to configuration file'); } } // close and save file flock($fp, LOCK_UN) or die ('ERROR: Cannot unlock file'); fclose($fp); echo 'Configuration data successfully written to file.'; } ?> </body> </html> This example illustrates a common, and practical, use of PHP’s file functions: to read and write configuration files in the context of a Web application. Figure 6-1 illustrates the Web form generated by this script. Once the form is submitted, the data entered into it arrives in the form of an associative array, whose keys correspond to the configuration variables in use. This data is then validated and a file pointer is opened to the configuration file, config.ini. A foreach loop then iterates over the array, writing the keys and values to the file pointer in key=value format, with each key-value pair on a separate line. The file pointer is then closed, saving the data to disk. Figure 6-1 A Web form to enter configuration data (continued) Here’s an example of what config.ini would look like after submitting the form in Figure 6-1: [email protected] DefAuthor=Charles W NumPosts=8 NumComments=4 If a user revisits the Web form, the script first checks if a configuration file named config.ini exists in the current directory. If it does, the lines of the file are read into an array with PHP’s file() function; a foreach loop then processes this array, splitting each line on the equality (=) symbol and turning the resulting key-value pairs into an
  • 30. associative array. This array is then used to prefill the form fields, by assigning a value to each input field’s 'value' attribute. Figure 6-2 illustrates one such Web form, prefilled with data read from the configuration file. Users are, of course, free to resubmit the form with new data; as explained previously, this submission will then be used to rewrite the configuration file with new values. Figure 6-2 A Web form prefilled with data from a configuration file Processing Directories PHP also allows developers to work with directories on the file system, iterating through directory contents or moving forward and backward through directory trees. Iterating through a directory is a simple matter of calling PHP’s DirectoryIterator object, as in the following example, which uses the DirectoryIterator to read a directory and list each file within it: <?php // initialize iterator with name of // directory to process $dit = new DirectoryIterator('.'); // loop over directory // print names of files found while($dit->valid()) { if (!$dit->isDot()) { echo $dit->getFilename() . "n"; } $dit->next(); } unset($dit); ?> Here, a DirectoryIterator object is initialized with a directory name, and the object’s rewind() method is used to reset the internal pointer to the first entry in the directory. A while loop, which runs so long as a valid() entry exists, can then be used to iterate over the directory. Individual filenames are retrieved with the getFilename() method, while the isDot() method can be used to filter out the entries for the current (.) and parent (..) directories. The next() method moves the internal pointer forward to the next entry. You can also accomplish the same task with a while loop and some of PHP’s directory manipulation functions . . . as in the following listing: <?php // create directory pointer $dp = opendir('.') or die ('ERROR: Cannot open directory'); // read directory contents // print filenames found while ($file = readdir($dp)) { if ($file != '.' && $file != '..') { echo "$file n"; } } // destroy directory pointer closedir($dp); ?> Here, the opendir() function returns a pointer to the directory named in the function call. This pointer is then used by the readdir() function to iterate over the directory, returning a single entry each time it is invoked. It’s then easy to filter out the . and .. directories, and print the names of the remaining entries. Once done, the closedir() function closes the file pointer. TIP Also consider PHP’s scandir() function, which accepts a directory name and returns an array containing a list of the files within that directory together with their sizes. It’s then easy to process this array with a foreach loop.
  • 31. In some cases, you might need to process not just the first-level directory, but also its subdirectories and sub-subdirectories. A recursive function, which you learned about in Chapter 5, is usually the best tool for this purpose: consider the next listing, which illustrates one such function in action: <?php // function definition // print names of files in a directory // and its child directories function printDir($dir, $depthStr='+') { if (file_exists($dir)) { // create directory pointer $dp = opendir($dir) or die ('ERROR: Cannot open directory'); // read directory contents // print names of files found // call itself recursively if directories found while ($file = readdir($dp)) { if ($file != '.' && $file != '..') { echo "$depthStr $dir/$file n"; if (is_dir("$dir/$file")) { printDir("$dir/$file", $depthStr.'+'); } } } // close directory pointer closedir($dp); } } // print contents of directory // and all children if (file_exists('.')) { echo '<pre>'; printDir('.'); echo '<pre>'; } ?> The printDir() function in this listing might appear complex, but it’s actually quite simple. It accepts two arguments: the name of the top-level directory to use, and a “depth string,” which indicates, via indentation, the position of a particular file or directory in the hierarchy. Using this input, the function opens a pointer to the named directory and begins processing it with readdir(), printing the name of each directory or file found. In the event that a directory is found, the depth string is incremented by an additional character and the printDir() function is itself recursively called to process that subdirectory. This process continues until no further files or directories remain to be processed. Figure 6-3 has an example of the output of this listing. Figure 6-3 An indented directory listing Performing Other File and Directory Operations In addition to the tools you’ve seen in previous sections, PHP comes with a whole range of file and directory manipulation functions, which allow you to check file attributes; copy, move, and delete files; and work with file paths and extensions. Table 6-1 lists some of the important functions in this category. Checking if a File or Directory Exists If you try reading or appending to a file that doesn’t exist, PHP will typically generate a fatal error. Ditto for attempts to access or read/write from/to a directory that doesn’t exist. To avoid these error messages, always check that the file or directory you’re attempting to access already exists, with PHP’s file_exists() function. The next listing illustrates it in action: Function What It Does file_exists() Tests if a file or directory exists filesize() Returns the size of a file in bytes realpath() Returns the absolute path of a file
  • 32. pathinfo() Returns an array of information about a file and its path stat() Provides information on file attributes and permissions is_readable() Tests if a file is readable is_writable() Tests if a file is writable is_executable() Tests if a file is executable is_dir() Tests if a directory entry is a directory is_file() Tests if a directory entry is a file copy() Copies a file rename() Renames a file unlink() Deletes a file mkdir() Creates a new directory rmdir() Removes a directory include() / require() Reads an external file into the current PHP script Table 6-1 Common PHP File and Directory Functions <?php // check file if (file_exists('somefile.txt')) { $str = file_get_contents('somefile.txt'); } else { echo 'Named file does not exist. '; } // check directory if (file_exists('somedir')) { $files = scandir('somedir'); } else { echo 'Named directory does not exist.'; } ?> Calculating File Size To calculate the size of a file in bytes, call the filesize() function with the filename as argument: <?php // get file size // output: 'File is 1327 bytes.' if (file_exists('example.txt')) { echo 'File is ' . filesize('example.txt') . ' bytes.'; } else { echo 'Named file does not exist. '; } ?> Finding the Absolute File Path To retrieve the absolute file system path to a file, use the realpath() function, as in the next listing: <?php // get file path // output: 'File path: /usr/local/apache/htdocs/ // /php-book/ch06/listings/example.txt' if (file_exists('example.txt')) { echo 'File path: ' . realpath('example.txt'); } else { echo 'Named file does not exist. '; } ?> Q: Are PHP’s file functions case-sensitive with respect to filenames? A: It depends on the underlying file system. Windows is case-insensitive with respect to filenames, so PHP’s file functions are case-insensitive too. However, filenames on *NIX systems are case-sensitive, and so PHP’s file functions are case-sensitive
  • 33. too on these systems. Thus, given the file eXAMple.txt, the statement <?php file_ exists('example.txt'); ?> might return false on a *NIX system but true on a Windows system. You can also use the pathinfo() function, which returns an array containing the file’s path, name, and extension. Here’s an example: <?php // get file path info as array if (file_exists('example.txt')) { print_r(pathinfo('example.txt')); } else { echo 'Named file does not exist. '; } ?> Retrieving File Attributes You can obtain detailed information on a particular file, including its ownership, permissions, and modification and access times, with PHP’s stat() function, which returns this information as an associative array. Here’s an example: <?php // get file information if (file_exists('example.txt')) { print_r(stat('example.txt')); } else { echo 'Named file does not exist. '; } ?> You can check if a file is readable, writable or executable with the is_readable(), is_writable(), and is_executable() functions. The following example illustrates their usage: <?php // get file information // output: 'File is: readable writable' if (file_exists('example.txt')) { echo 'File is: '; // check for readable bit if (is_readable('example.txt')) { echo ' readable '; } // check for writable bit if (is_writable('example.txt')) { echo ' writable '; } // check for executable bit if (is_executable('example.txt')) { echo ' executable '; } } else { echo 'Named file does not exist. '; } ?> The is_dir() function returns true if the argument passed to it is a directory, while the is_file() function returns true if the argument passed to it is a file. Here’s an example: <?php // test if file or directory if (file_exists('example.txt')) { if (is_file('example.txt')) { echo 'It's a file.'; } if (is_dir('example.txt')) { echo 'It's a directory.';
  • 34. } } else { echo 'ERROR: File does not exist.'; } ?> Creating Directories To create a new, empty directory, call the mkdir() function with the path and name of the directory to be created: <?php if (!file_exists('mydir')) { if (mkdir('mydir')) { echo 'Directory successfully created.'; } else { echo 'ERROR: Directory could not be created.'; } } else { echo 'ERROR: Directory already exists.'; } ?> Copying Files You can copy a file from one location to another by calling PHP’s copy() function with the file’s source and destination paths as arguments. Here’s an example: <?php // copy file if (file_exists('example.txt')) { if (copy('example.txt', 'example.new.txt')) { echo 'File successfully copied.'; } else { echo 'ERROR: File could not be copied.'; } } else { echo 'ERROR: File does not exist.'; } ?> It’s important to note that if the destination file already exists, the copy() function will overwrite it. Renaming Files or Directories To rename or move a file (or directory), call PHP’s rename() function with the old and new path names as arguments. Here’s an example that renames a file and a directory, moving the file to a different location in the process: <?php // rename/move file if (file_exists('example.txt')) { if (rename('example.txt', '../example.new.txt')) { echo 'File successfully renamed.'; } else { echo 'ERROR: File could not be renamed.'; } } else { echo 'ERROR: File does not exist.'; } // rename directory if (file_exists('mydir')) { if (rename('mydir', 'myotherdir')) { echo 'Directory successfully renamed.'; } else { echo 'ERROR: Directory could not be renamed.'; }
  • 35. } else { echo 'ERROR: Directory does not exist.'; } ?> As with copy(), if the destination file already exists, the rename() function will overwrite it. CAUTION PHP will only allow you to copy, delete, rename, create, and otherwise manipulate a file or directory if the user "owning" the PHP script has the privileges necessary to perform the task. Removing Files or Directories To remove a file, pass the filename and path to PHP’s unlink() function, as in the following example: <?php // delete file if (file_exists('dummy.txt')) { if (unlink('dummy.txt')) { echo 'File successfully removed.'; } else { echo 'ERROR: File could not be removed.'; } } else { echo 'ERROR: File does not exist.'; } ?> To remove an empty directory, PHP offers the rmdir() function, which does the reverse of the mkdir() function. If the directory isn’t empty, though, it’s necessary to first remove all its contents (including all subdirectories) and only then call the rmdir() function to remove the directory. You can do this manually, but a recursive function is usually more efficient—here’s an example, which demonstrates how to remove a directory and all its children: <?php // function definition // remove all files in a directory function removeDir($dir) { if (file_exists($dir)) { // create directory pointer $dp = opendir($dir) or die ('ERROR: Cannot open directory'); // read directory contents // delete files found // call itself recursively if directories found while ($file = readdir($dp)) { if ($file != '.' && $file != '..') { if (is_file("$dir/$file")) { unlink("$dir/$file"); } else if (is_dir("$dir/$file")) { removeDir("$dir/$file"); } } } // close directory pointer // remove now-empty directory closedir($dp); if (rmdir($dir)) { return true; } else { return false; } } }
  • 36. // delete directory and all children if (file_exists('mydir')) { if (removeDir('mydir')) { echo 'Directory successfully removed.'; } else { echo 'ERROR: Directory could not be removed.'; } } else { echo 'ERROR: Directory does not exist.'; } ?> Here, the removeDir() function is a recursive function that accepts one input argument: the name of the top-level directory to remove. The function begins by creating a pointer to the directory with opendir() and then iterating over the directory’s contents with a while loop—you’ve seen this technique in a previous section of this chapter. For each directory entry found, the is_file() and is_dir() methods are used to determine if the entry is a file or a sub-directory; if the former, the unlink() function is used to delete the file and if the latter, the removeDir() function is called recursively to again process the subdirectory’s contents. This process continues until no files or subdirectories are left; at this point, the top-level directory is empty and can be removed with a quick rmdir(). Reading and Evaluating External Files To read and evaluate external files from within your PHP script, use PHP’s include() or require() function. A very common application of these functions is to include a standard header, footer, or copyright notice across all the pages of a Web site. Here’s an example: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title></title> </head> <body> <?php require('header.php'); ?> <p/> This is the page body. <p/> <?php include('footer.php'); ?> </body> </html> Here, the script reads two external files, header.php and footer.php, and places the contents of these files at the location of the include() or require() call. It’s important to note that any PHP code to be evaluated within the files included in this manner must be enclosed within <?php ... ?> tags. Q: What is the difference between include() and require()? A: Fairly simple: a missing include() will generate a warning but allow script execution to continue, whereas a missing require() will generate a fatal error that halts script execution.