Filesystem functionsFilesystembasenamereturn filename component of pathDescriptionstring basenamestring path
Given a string containing a path to a file, this function will
return the base name of the file.
On Windows, both slash (/) and backslash
(\) are used as path separator character. In
other environments, it is the forward slash
(/).basename example
$path = "/home/httpd/html/index.php3";
$file = basename($path); // $file is set to "index.php3"
See also:
dirnamechgrpchange file groupDescriptionint chgrpstring filenamemixed group
Attempts to change the group of the file filename to group. Only
the superuser may change the group of a file arbitrarily; other
users may change the group of a file to any group of which that
user is a member.
Returns true on success; otherwise returns false.
On Windows, does nothing and returns true.
See also chown and chmod.chmodchange file modeDescriptionint chmodstring filenameint mode
Attempts to change the mode of the file specified by
filename to that given in
mode.
Note that mode is not automatically
assumed to be an octal value. To ensure the expected operation,
you need to prefix mode with a zero (0):
chmod( "/somedir/somefile", 755 ); // decimal; probably incorrect
chmod( "/somedir/somefile", 0755 ); // octal; correct value of mode
Returns true on success and false otherwise.
See also chown and chgrp.chownchange file ownerDescriptionint chownstring filenamemixed user
Attempts to change the owner of the file filename to user
user. Only the superuser may change the owner of a file.
Returns true on success; otherwise returns false.
On Windows, does nothing and returns true.
See also chown and chmod.clearstatcacheclear file stat cacheDescriptionvoid clearstatcache
Invoking the stat or
lstat system call on most systems is quite
expensive. Therefore, the result of the last call to any of the
status functions (listed below) is stored for use on the next
such call using the same filename. If you wish to force a new
status check, for instance if the file is being checked many
times and may change or disappear, use this function to clear the
results of the last call from memory.
This value is only cached for the lifetime of a single request.
Affected functions include stat,
lstat,
file_exists,
is_writeable,
is_readable,
is_executable,
is_file,
is_dir,
is_link,
filectime,
fileatime,
filemtime,
fileinode,
filegroup,
fileowner,
filesize,
filetype, and
fileperms.copycopy fileDescriptionint copystring sourcestring dest
Makes a copy of a file. Returns true if the copy succeeded,
false otherwise.
copy example
if (!copy($file, $file.'.bak')) {
print("failed to copy $file...<br>\n");
}
See also:
renamedeletea dummy manual entryDescriptionvoid deletestring file
This is a dummy manual entry to satisfy those people who are
looking for unlink or
unset in the wrong place.
See also:
unlink to delete files, unset
to delete variables.dirnamereturn directory name component of pathDescriptionstring dirnamestring path
Given a string containing a path to a file, this function will
return the name of the directory.
On Windows, both slash (/) and backslash
(\) are used as path separator character. In
other environments, it is the forward slash
(/).dirname example
$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"
See also:
basenamediskfreespacereturn available space in directoryDescriptionfloat diskfreespacestring directory
Given a string containing a directory, this function will
return the number of bytes available on the corresponding
disk.diskfreespace example
$df = diskfreespace("/"); // $df contains the number of bytes available on "/"
fcloseclose an open file pointerDescriptionint fcloseint fp
The file pointed to by fp is closed.
Returns true on success and false on failure.
The file pointer must be valid, and must point to a file
successfully opened by fopen or
fsockopen.feoftest for end-of-file on a file pointerDescriptionint feofint fp
Returns true if the file pointer is at EOF or an error occurs;
otherwise returns false.
The file pointer must be valid, and must point to a file
successfully opened by fopen,
popen, or fsockopen.fgetcget character from file pointerDescriptionstring fgetcint fp
Returns a string containing a single character read from the
file pointed to by fp. Returns FALSE on EOF (as does
feof).
The file pointer must be valid, and must point to a file
successfully opened by fopen,
popen, or fsockopen. See also fread, fopen,
popen, fsockopen, and
fgets.fgetcsvget line from file pointer and parse for CSV fieldsDescriptionarray fgetcsvint fpint lengthstring delimiter
Similar to fgets() except that fgetcsv() parses the line it reads for
fields in CSV format and returns an array containing the fields read.
The field delimiter is a comma, unless you specifiy another
delimiter with the optional third parameter.
fp must be a valid file pointer to a file successfully opened by
fopen, popen, or fsockopen
length must be greater than the longest line to be found in the CSV
file (allowing for trailing line-end characters).
fgetcsv() returns false on error, including end of file.
NB A blank line in a CSV file will be returned as an array comprising
just one single null field, and will not be treated as an error.fgetcsv() example - Read and print entire contents of a CSV file
$row=1;
$fp = fopen("test.csv","r");
while ($data = fgetcsv($fp,1000, ",")) {
$num = count($data);
print "<p> $num fields in line $row: <br>";
$row++;
for ( $c=0; $c<$num; $c++ ) print $data[$c] . "<br>";
}
fclose($fp);
fgetsget line from file pointerDescriptionstring fgetsint fpint length
Returns a string of up to length - 1 bytes read from the file
pointed to by fp. Reading ends when length - 1 bytes have been
read, on a newline (which is included in the return value), or
on EOF (whichever comes first).
If an error occurs, returns false.
Common Pitfalls:
People used to the 'C' semantics of fgets should note the difference
in how EOF is returned.
The file pointer must be valid, and must point to a file
successfully opened by fopen,
popen, or fsockopen.
A simple example follows:
Reading a file line by line
$fd = fopen("/tmp/inputfile.txt", "r");
while (!feof($fd)) {
$buffer = fgets($fd, 4096);
echo $buffer;
}
fclose($fd);
See also fread,
fopen, popen,
fgetc, and fsockopen.fgetssget line from file pointer and strip HTML tagsDescriptionstring fgetssint fpint lengthstring allowable_tags
Identical to fgets,
except that fgetss attempts to strip any HTML and PHP tags from
the text it reads.
You can use the optional third parameter to specify tags which
should not be stripped.
allowable_tags was added in PHP 3.0.13, PHP4B3.
See also fgets, fopen,
fsockopen, popen,
and strip_tags.fileread entire file into an arrayDescriptionarray filestring filenameint use_include_path
Identical to readfile, except that file
returns the file in an array. Each element of the array corresponds
to a line in the file, with the newline still attached.
You can use the optional second parameter and set it to "1", if
you want to search for the file in the include_path, too.
See also readfile,
fopen, and popen.file_existsCheck whether a file exists.Descriptionint file_existsstring filename
Returns true if the file specified by
filename exists; false otherwise.
The results of this function are cached. See
clearstatcache for more details.fileatimeget last access time of fileDescriptionint fileatimestring filename Returns the time the file was last accessed, or false in case
of an error.
The results of this function are cached. See
clearstatcache for more details.filectimeget inode change time of fileDescriptionint filectimestring filename
Returns the time the file was last changed, or false in case of
an error.
The results of this function are cached. See
clearstatcache for more details.filegroupget file groupDescriptionint filegroupstring filename Returns the group ID of the owner of the file, or false in case of an
error.
The results of this function are cached. See
clearstatcache for more details.fileinodeget file inodeDescriptionint fileinodestring filename
Returns the inode number of the file, or false in case of an
error.
The results of this function are cached. See
clearstatcache for more details.filemtimeget file modification timeDescriptionint filemtimestring filename
Returns the time the file was last modified, or false in case of
an error.
The results of this function are cached. See
clearstatcache for more details.fileownerget file ownerDescriptionint fileownerstring filename Returns the user ID of the owner of the file, or false in case of an
The results of this function are cached. See
clearstatcache for more details.
error.filepermsget file permissionsDescriptionint filepermsstring filename
Returns the permissions on the file, or false in case of an error.
The results of this function are cached. See
clearstatcache for more details.filesizeget file sizeDescriptionint filesizestring filename Returns the size of the file, or false in case of an error.
The results of this function are cached. See
clearstatcache for more details.filetypeget file typeDescriptionstring filetypestring filename Returns the type of the file. Possible values are
fifo, char, dir,
block, link, file, and
unknown. Returns false if an error occurs.
The results of this function are cached. See
clearstatcache for more details.flockportable advisory file lockingDescriptionbool flockint fpint operation
PHP supports a portable way of locking complete files in an advisory way
(which means all accessing programs have to use the same way of locking
or it will not work).flock operates on fp which
must be an open file pointer. operation is one of
the following values:
To acquire a shared lock (reader), set operation
to 1.
To acquire an exclusive lock (writer), set
operation to 2.
To release a lock (shared or exclusive), set
operation to 3.
If you don't want flock to block while locking,
add 4 to operation.flock allows you to perform a simple reader/writer
model which can be used on virtually every platform (including most
Unices and even Windows).flock returns true on success and false on error
(e.g. when a lock could not be acquired).fopenopen file or URLDescriptionint fopenstring filenamestring modeint use_include_path
If filename begins with "http://" (not case sensitive), an HTTP
1.0 connection is opened to the specified server and a file
pointer is returned to the beginning of the text of the response.
Does not handle HTTP redirects, so you must include trailing
slashes on directories.
If filename begins with "ftp://" (not case sensitive), an ftp
connection to the specified server is opened and a pointer to the
requested file is returned. If the server does not support
passive mode ftp, this will fail. You can open files for either
reading and writing via ftp (but not both simultaneously).
If filename begins with anything else, the
file will be opened from the filesystem, and a file pointer to
the file opened is returned.
If the open fails, the function returns false.mode may be any of the following:
'r' - Open for reading only; place the file
pointer at the beginning of the file.
'r+' - Open for reading and writing; place the file pointer at
the beginning of the file.
'w' - Open for writing only; place the file pointer at the
beginning of the file and truncate the file to zero length.
If the file does not exist, attempt to create it.
'w+' - Open for reading and writing; place the file pointer at
the beginning of the file and truncate the file to zero length.
If the file does not exist, attempt to create it.
'a' - Open for writing only; place the file pointer at the end
of the file. If the file does not exist, attempt to create it.
'a+' - Open for reading and writing; place the file pointer at
the end of the file. If the file does not exist, attempt to
create it.
As well, mode may contain the letter
'b'. This is useful only on systems which differentiate between
binary and text files (i.e., it's useless on Unix). If not
needed, this will be ignored.
You can use the optional third parameter and set it to "1", if
you want to search for the file in the include_path, too.fopen() example
$fp = fopen("/home/rasmus/file.txt", "r");
$fp = fopen("http://www.php.net/", "r");
$fp = fopen("ftp://user:password@example.com/", "w");
If you are experiencing problems with reading and writing to
files and you're using the server module version of PHP, remember
to make sure that the files and directories you're using are
accessible to the server process.
On the Windows platform, be careful to escape any backslashes
used in the path to the file, or use forward slashes.
$fp = fopen("c:\\data\\info.txt", "r");
See also fclose,
fsockopen, and popen.fpassthruoutput all remaining data on a file pointerDescriptionint fpassthruint fp
Reads to EOF on the given file pointer and writes the results to
standard output.
If an error occurs, fpassthru returns false.
The file pointer must be valid, and must point to a file successfully
opened by fopen, popen, or
fsockopen. The file is closed when
fpassthru is done reading it (leaving
fp useless).
If you just want to dump the contents of a file to stdout
you may want to use the readfile, which
saves you the fopen call.
See also readfile, fopen,
popen, and fsockopenfputswrite to a file pointerDescriptionint fputsint fpstring strint lengthfputs is an alias to
fwrite, and is identical in every way. Note that the
length parameter is optional and if not specified the
entire string will be written.freadBinary-safe file readDescriptionstring freadint fpint lengthfread reads up to
length bytes from the file pointer
referenced by fp. Reading stops when
length bytes have been read or EOF is
reached, whichever comes first.
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$fd = fopen( $filename, "r" );
$contents = fread( $fd, filesize( $filename ) );
fclose( $fd );
See also fwrite, fopen,
fsockopen, popen,
fgets, fgetss,
file, and fpassthru.fseekseek on a file pointerDescriptionint fseekint fpint offset
Sets the file position indicator for the file referenced by fp to
offset bytes into the file stream. Equivalent to calling (in C)
fseek( fp, offset, SEEK_SET ).
Upon success, returns 0; otherwise, returns -1. Note that seeking
past EOF is not considered an error.
May not be used on file pointers returned by fopen
if they use the "http://" or "ftp://" formats.
See also ftell and
rewind.ftelltell file pointer read/write positionDescriptionint ftellint fp
Returns the position of the file pointer referenced by fp; i.e.,
its offset into the file stream.
If an error occurs, returns false.
The file pointer must be valid, and must point to a file
successfully opened by fopen or
popen. See also fopen,
popen, fseek and
rewind.fwriteBinary-safe file writeDescriptionint fwriteint fpstring stringint lengthfwrite writes the contents of
string to the file stream pointed to by
fp. If the length
argument is given, writing will stop after
length bytes have been written or the end
of string is reached, whichever comes
first.
Note that if the length argument is given,
then the magic_quotes_runtime
configuration option will be ignored and no slashes will be
stripped from string.
See also fread, fopen,
fsockopen, popen, and
fputs.set_file_bufferSets file buffering on the given file pointerDescriptionint fwriteint fpint bufferset_file_buffer sets the buffering for write
operations on the given filepointer fp to
buffer bytes. If buffer
is 0 then write operations are unbuffered.
The function returns 0 on success, or EOF if the request cannot
be honored.
Note that the default for any fopen with calling set_file_buffer
is 8K.
See also fopen.is_dirtells whether the filename is a directoryDescriptionbool is_dirstring filename
Returns true if the filename exists and is a directory.
The results of this function are cached. See
clearstatcache for more details.
See also is_file and is_link.is_executabletells whether the filename is executableDescriptionbool is_executablestring filename
Returns true if the filename exists and is executable.
The results of this function are cached. See
clearstatcache for more details.
See also is_file and is_link.is_filetells whether the filename is a regular fileDescriptionbool is_filestring filename
Returns true if the filename exists and is a regular file.
The results of this function are cached. See
clearstatcache for more details.
See also is_dir and is_link.is_linktells whether the filename is a symbolic linkDescriptionbool is_linkstring filename
Returns true if the filename exists and is a symbolic link.
The results of this function are cached. See
clearstatcache for more details.
See also is_dir and is_file.is_readabletells whether the filename is readableDescriptionbool is_readablestring filename
Returns true if the filename exists and is readable.
Keep in mind that PHP may be accessing the file as the user
id that the web server runs as (often 'nobody'). Safe mode
limitations are not taken into account.
The results of this function are cached. See
clearstatcache for more details.
See also is_writeable.is_writeabletells whether the filename is writeableDescriptionbool is_writeablestring filename
Returns true if the filename exists and is writeable. The filename
argument may be a directory name allowing you to check if a
directory is writeable.
Keep in mind that PHP may be accessing the file as the user
id that the web server runs as (often 'nobody'). Safe mode
limitations are not taken into account.
The results of this function are cached. See
clearstatcache for more details.
See also is_readable.linkCreate a hard linkDescriptionint linkstring targetstring linkLink creates a hard link.
See also the symlink to create soft links,
and readlink along with linkinfo.linkinfoGet information about a linkDescriptionint linkinfostring pathLinkinfo returns the st_dev field of the UNIX C
stat structure returned by the lstat system call. This
function is used to verify if a link (pointed to by path)
really exists (using the same method as the S_ISLNK macro defined in stat.h).
Returns 0 or FALSE in case of error.
See also symlink, link,
and readlink.mkdirmake directoryDescriptionint mkdirstring pathnameint mode
Attempts to create the directory specified by pathname.
Note that you probably want to specify the mode as an
octal number, which means it should have a leading zero.
mkdir("/path/to/my/dir", 0700);
Returns true on success and false on failure.
See also rmdir.pcloseclose process file pointerDescriptionint pcloseint fp Closes a file pointer to a pipe opened by popen. The file pointer must be valid, and must have been returned by a
successful call to popen. Returns the termination status of the process that was run.
See also popen.popenopen process file pointerDescriptionint popenstring commandstring mode Opens a pipe to a process executed by forking the command
given by command. Returns a file pointer identical to that returned by
fopen, except that it is unidirectional
(may only be used for reading or writing) and must be closed with
pclose. This pointer may be used
with fgets, fgetss, and
fputs.
If an error occurs, returns false.
$fp = popen( "/bin/ls", "r" );
See also pclose.readfileoutput a fileDescriptionint readfilestring filenameint use_include_path
Reads a file and writes it to standard output.
Returns the number of bytes read from the file. If an error
occurs, false is returned and unless the function was called as
@readfile, an error message is printed.
If filename begins with "http://"
(not case sensitive), an HTTP 1.0 connection is opened to the
specified server and the text of the response is written to
standard output.
Does not handle HTTP redirects, so you must include trailing
slashes on directories.
If filename begins with "ftp://"
(not case sensitive), an ftp connection to the specified server is
opened and the requested file is written to standard output. If the server
does not support passive mode ftp, this will fail.
If filename begins with neither
of these strings, the file will be opened from the filesystem and
its contents written to standard output.
You can use the optional second parameter and set it to "1", if
you want to search for the file in the include_path, too.
See also fpassthru, file,
fopen, include,
require, and virtual.readlinkReturn the target of a symbolic linkDescriptionstring readlinkstring pathReadlink does the same as the readlink C function
and returns the contents of the symbolic link path or 0 in case of error.
See also symlink,
readlink and linkinfo.renamerename a fileDescriptionint renamestring oldnamestring newname Attempts to rename oldname to newname. Returns true on success and false on failure.rewindrewind the position of a file pointerDescriptionint rewindint fp Sets the file position indicator for fp to the
beginning of the file stream. If an error occurs, returns 0. The file pointer must be valid, and must point to a file
successfully opened by fopen.
See also fseek and ftell.rmdirremove directoryDescriptionint rmdirstring dirname Attempts to remove the directory named by pathname. The
directory must be empty, and the relevant permissions must permit
this. If an error occurs, returns 0.
See also mkdir.statgive information about a fileDescriptionarray statstring filename
Gathers the statistics of the file named by filename.
Returns an array with the statistics of the file with the
following elements:
deviceinodeinode protection modenumber of linksuser id of ownergroup id ownerdevice type if inode device *size in bytestime of last accesstime of last modificationtime of last changeblocksize for filesystem I/O *number of blocks allocated
* - only valid on systems supporting the st_blksize type--other
systems (i.e. Windows) return -1
The results of this function are cached. See
clearstatcache for more details.lstatgive information about a file or symbolic linkDescriptionarray lstatstring filename
Gathers the statistics of the file or symbolic link named by filename.
This function is identical to the stat function
except that if the filename parameter is a
symbolic link, the status of the symbolic link is returned, not
the status of the file pointed to by the symbolic link.
Returns an array with the statistics of the file with the
following elements:
deviceinodenumber of linksuser id of ownergroup id ownerdevice type if inode device *size in bytestime of last accesstime of last modificationtime of last changeblocksize for filesystem I/O *number of blocks allocated
* - only valid on systems supporting the st_blksize type--other
systems (i.e. Windows) return -1
The results of this function are cached. See
clearstatcache for more details.symlinkCreate a symbolic linkDescriptionint symlinkstring targetstring linksymlink creates a symbolic link
from the existing target with
the specified name link.
See also link to create hard links,
and readlink along with
linkinfo.tempnamcreate unique file nameDescriptionstring tempnamstring dirstring prefix
Creates a unique temporary filename in the specified directory.
If the directory does not exist, tempnam
may generate a filename in the system's temporary directory.
The behaviour of the tempnam function is
system dependent. On Windows the TMP environment variable will
override the dir parameter, on Linux the
TMPDIR environment variable has precedence, while SVR4 will always
use your dir parameter if the directory it
points to exists. Consult your system documentation on the
tempnam(3) function if in doubt.
Returns the new temporary filename, or the null string on
failure.
tempnam() example
$tmpfname = tempnam( "/tmp", "FOO" );
touchset modification time of fileDescriptionint touchstring filenameint time
Attempts to set the modification time of the file named by
filename to the value given by time. If the option time is not
given, uses the present time.
If the file does not exist, it is created.
Returns true on success and false otherwise.umaskchanges the current umaskDescriptionint umaskint maskUmask sets PHP's umask to mask & 0777 and returns the
old umask. When PHP is being used as a server module, the umask is restored
when each request is finished.Umask without arguments simply returns the current umask.unlinkDelete a fileDescriptionint unlinkstring filename
Deletes filename. Similar to the Unix C unlink() function.
Returns 0 or FALSE on an error.
See also rmdir for removing directories.