Filesystem functionsFilesystem
For related functions, see also the Directory
and Program Execution sections.
basenameReturns filename component of pathDescriptionstringbasenamestringpathstringsuffix
Given a string containing a path to a file, this function will
return the base name of the file.
If the filename ends in suffix this will
also be cut off.
On Windows, both slash (/) and backslash
(\) are used as path separator character. In
other environments, it is the forward slash
(/).
basename example
The suffix parameter was added in PHP 4.1.0.
See also: dirnamechgrpChanges file groupDescriptionintchgrpstringfilenamemixedgroup
Attempts to change the group of the file filename
to group (specified by name or number). 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.
&return.success;
See also chown and
chmod.
¬e.no-windows;
chmodChanges file modeDescriptionintchmodstringfilenameintmode
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, so strings (such as "g+w") will
not work properly. To ensure the expected operation,
you need to prefix mode with a zero (0):
&return.success;
See also chown and
chgrp.
¬e.no-windows;
chownChanges file ownerDescriptionintchownstringfilenamemixeduser
Attempts to change the owner of the file filename
to user user (specified by name or number). Only
the superuser may change the owner of a file.
&return.success;
See also chown and
chmod.
¬e.no-windows;
clearstatcacheClears file stat cacheDescriptionvoidclearstatcache
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_writable,
is_readable,
is_executable,
is_file,
is_dir,
is_link,
filectime,
fileatime,
filemtime,
fileinode,
filegroup,
fileowner,
filesize,
filetype, and
fileperms.
copyCopies fileDescriptionintcopystringsourcestringdest
Makes a copy of a file. Returns &true; if the copy succeeded,
&false; otherwise.
copy example
\n");
}
]]>
As of PHP 4.3.0, both source and
dest may be URLs if the "fopen wrappers"
have been enabled. See fopen for more details.
If the destination file already exists, it will be overwritten.
See also move_uploaded_file,
rename, and the section of the manual
about handling file
uploads.
deleteA dummy manual entryDescriptionvoiddeletestringfile
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.
dirnameReturns directory name component of pathDescriptionstringdirnamestringpath
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
In PHP 4.0.3, dirname was fixed to be
POSIX-compliant. Essentially, this means that if there are no
slashes in path , a dot
('.') is returned, indicating the current
directory. Otherwise, the returned string is
path with any trailing
/component removed. Note that this means that
you will often get a slash or a dot back from
dirname in situations where the older
functionality would have given you the empty string.
See also: basenamedisk_free_spaceReturns available space in directoryDescriptionfloatdisk_free_spacestringdirectory
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 examplediskfreespaceAlias of disk_free_spaceDescriptionfloatdiskfreespacestringdirectory
This is a deprecated alias of
disk_free_space.
Use that function instead.
disk_total_spaceReturns the total size of a directoryDescriptionfloatdisk_total_spacestringdirectory
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 examplefcloseCloses an open file pointerDescriptionboolfcloseintfp
The file pointed to by fp is closed.
&return.success;
The file pointer must be valid, and must point to a file
successfully opened by fopen or
fsockopen.
feofTests for end-of-file on a file pointerDescriptionintfeofintfp
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.
fflushFlushes the output to a fileDescriptionintfflushintfp
This function forces a write of all buffered output to the
to the resource pointed to by the file handle
fp. Returns &true; if successful, &false;
otherwise.
The file pointer must be valid, and must point to a file
successfully opened by fopen,
popen, or fsockopen.
fgetcGets character from file pointerDescriptionstringfgetcintfp
Returns a string containing a single character read from the
file pointed to by fp. Returns &false; on EOF.
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.
fgetcsvGets line from file pointer and parse for CSV fieldsDescriptionarrayfgetcsvintfpintlengthstringdelimiter
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
specify 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.
N.B. A blank line in a CSV file will be returned as an array
comprising a single &null; field, and will not be treated as an
error.
fgetcsv example - Read and print entire
contents of a CSV file
$num fields in line $row: ";
$row++;
for ($c=0; $c < $num; $c++) {
print $data[$c] . " ";
}
}
fclose ($fp);
]]>
fgetsGets line from file pointerDescriptionstringfgetsintfpintlength
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 no length is specified, the length
defaults to 1k, or 1024 bytes.
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
The length parameter became optional in PHP 4.2.0
See also fread, fopen,
popen, fgetc,
fsockopen, and
socket_set_timeout.
fgetssGets line from file pointer and strip HTML tagsDescriptionstringfgetssintfpintlengthstringallowable_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,
PHP 4.0.0.
See also fgets, fopen,
fsockopen, popen, and
strip_tags.
file_register_wrapperRegister a URL wrapper implemented as a PHP classDescriptionbooleanfile_register_wrapperstringprotocolstringclassname
This function is currently only documented by the example below:
Implementing a base64 encoding protocol
fp = fopen($path, $mode);
return is_resource($this->fp);
}
function stream_close()
{
fclose($this->fp);
}
function stream_read($count)
{
return false; // We only allow writing
}
function stream_write($data)
{
return fwrite($this->fp, base64_encode($data));
}
function stream_flush()
{
fflush($this->fp);
return true;
}
function stream_seek($offset, $whence)
{
return false;
}
function stream_gets()
{
return false;
}
function stream_tell()
{
return false;
}
function stream_eof()
{
return false;
}
}
file_register_wrapper("base64", "Base64EncodingStream")
or die("Failed to register protocol");
copy("/tmp/inputfile.txt", "base64:///tmp/outputfile.txt");
readfile("/tmp/outputfile");
]]>
file_register_wrapper will return false if the
protocol already has a handler, or if "fopen
wrappers" are disabled.
This function was introduced in PHP 4.3.0.
file_get_contentsReads entire file into a stringDescriptionstringfile_get_contentsstringfilenameintuse_include_path
Identical to readfile, except that
file_get_contents returns the file in a string.
This function was introduced in PHP 4.3.0.
¬e.bin-safe;
&tip.fopen-wrapper;
fileReads entire file into an arrayDescriptionarrayfilestringfilenameintuse_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.
Each line in the resulting array will include the line ending, so you
still need to use trim if you do not want the line
ending present.
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.
Line $line_num:; ", htmlspecialchars ($line), " \n";
}
// get a web page into a string
$fcontents = implode ('', file ('http://www.example.com/'));
?>
]]>
As of PHP 4.3.0 you can use file_get_contents to
return the contents of a file as a string in a binary safe manner.
¬e.not-bin-safe;
&tip.fopen-wrapper;
See also readfile,
fopen, fsockopen, and
popen.
file_existsChecks whether a file existsDescriptionboolfile_existsstringfilename
Returns &true; if the file specified by
filename exists; &false; otherwise.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
The results of this function are cached. See
clearstatcache for more details.
On windows use "//computername/share/filename" or
"\\\\computername\share\filename" to check files on
network shares.
fileatimeGets last access time of fileDescriptionintfileatimestringfilename
Returns the time the file was last accessed, or &false; in case of
an error. The time is returned as a Unix timestamp.
The results of this function are cached. See
clearstatcache for more details.
Note: The atime of a file is supposed to change whenever
the data blocks of a file are being read. This can be
costly performancewise when an application regularly
accesses a very large number of files or directories. Some
Unix filesystems can be mounted with atime updates disabled
to increase the performance of such applications; USENET
news spools are a common example. On such filesystems
this function will be useless.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
filectimeGets inode change time of fileDescriptionintfilectimestringfilename
Returns the time the file was last changed, or &false; in case of
an error. The time is returned as a Unix timestamp.
The results of this function are cached. See
clearstatcache for more details.
Note: In most Unix filesystems, a file is considered
changed when its inode data is changed; that is, when
the permissions, owner, group, or other metadata
from the inode is updated. See also
filemtime (which is what you want to use
when you want to create "Last Modified" footers on web pages) and
fileatime.
Note also that in some Unix texts the ctime of a file is
referred to as being the creation time of the file. This is wrong.
There is no creation time for Unix files in most Unix filesystems.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
filegroupGets file groupDescriptionintfilegroupstringfilename
Returns the group ID of the owner of the file, or &false; in case
of an error. The group ID is returned in numerical format, use
posix_getgrgid to resolve it to a group name.
The results of this function are cached. See
clearstatcache for more details.
¬e.no-windows;
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
fileinodeGets file inodeDescriptionintfileinodestringfilename
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.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
¬e.no-windows;
filemtimeGets file modification timeDescriptionintfilemtimestringfilename
Returns the time the file was last modified, or &false; in case of
an error. The time is returned as a Unix timestamp.
The results of this function are cached. See
clearstatcache for more details.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
Note: 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. Use
date on the result of this function
to get a printable modification date for use in page footers.
See also filectime and touch.
fileownerGets file ownerDescriptionintfileownerstringfilename
Returns the user ID of the owner of the file, or &false; in case of
an error. The user ID is returned in numerical format, use
posix_getpwuid to resolve it to a username.
The results of this function are cached. See
clearstatcache for more details.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
¬e.no-windows;
filepermsGets file permissionsDescriptionintfilepermsstringfilename
Returns the permissions on the file, or &false; in case of an error.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
The results of this function are cached. See
clearstatcache for more details.
filesizeGets file sizeDescriptionintfilesizestringfilename
Returns the size of the file in bytes, or &false; in case of an error.
The results of this function are cached. See
clearstatcache for more details.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
filetypeGets file typeDescriptionstringfiletypestringfilename
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.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
flockPortable advisory file lockingDescriptionboolflockintfpintoperationintwouldblock
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 LOCK_SH (set to 1 prior to
PHP 4.0.1).
To acquire an exclusive lock (writer), set
operation to LOCK_EX (set to 2 prior to
PHP 4.0.1).
To release a lock (shared or exclusive), set
operation to LOCK_UN (set to 3 prior to
PHP 4.0.1).
If you don't want flock to block while
locking, add LOCK_NB (4 prior to PHP 4.0.1) to
operation.
flock allows you to perform a simple
reader/writer model which can be used on virtually every platform
(including most Unix derivatives and even Windows). The optional third
argument is set to &true; if the lock would block (EWOULDBLOCK
errno condition)
flock returns &true; on success and &false; on
error (e.g. when a lock could not be acquired).
Because flock requires a file pointer, you may have
to use a special lock file to protect access to a file that you intend
to truncate by opening it in write mode (with a "w" or "w+" argument to
fopen).
flock will not work on NFS and many other networked
file systems. Check your operating system documentation for more
details.
On some operating systems flock is implemented at
the process level. When using a multithreaded server API like ISAPI you
may not be able to rely on flock to protect files
against other PHP scripts running in parallel threads of the same server
instance!
file_get_wrapper_dataRetrieves header/meta data from "wrapped" file pointersDescriptionmixedfile_get_wrapper_dataintfp
This function returns header or meta data from files opened with
fopen. This is useful to return the response
headers for HTTP connections, or some other statistics for other
resources.
The format of the returned data is deliberately undocumented at this
time, and depends on which wrapper(s) were used to open the file.
This function was introduced in PHP 4.3.0.
fopenOpens file or URLDescriptionintfopenstringfilenamestringmodeintuse_include_path
If filename begins with "http://" (not
case sensitive), an HTTP 1.0 connection is opened to the
specified server, the page is requested using the HTTP GET
method, and a file pointer is returned to the beginning
of the body of the response. A 'Host:' header is sent with the
request in order to handle name-based virtual hosts.
As of PHP 4.3.0 (not yet released), if you have compiled in
support for OpenSSL, you may use "https://" to open an HTTP
connection over SSL.
Note that the file pointer allows you to retrieve only the
body of the response; to retrieve the HTTP
response header you need to be using PHP 4.0.5 or later;
The headers will be stored in the $http_response_header variable.
As of PHP 4.3.0 (not yet released), the header information can
be retrieved using the file_get_wrapper_data.
HTTP connections are read-only; you cannot write data or copy
files to an HTTP resource.
Versions prior to PHP 4.0.5 do not handle HTTP redirects. Because
of this, directories must include trailing slashes.
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 or writing via ftp (but not both
simultaneously). If the remote file already exists on the ftp
server and you attempt to open it for writing, this will fail.
If you need to update existing files over ftp, use
ftp_connect.
If filename is one of "php://stdin",
"php://stdout", or "php://stderr", the corresponding stdio
stream will be opened. (This was introduced in PHP 3.0.13;
in earlier versions, a filename such as "/dev/stdin" or
"/dev/fd/0" must be used to access the stdio streams.)
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.
The mode may contain the letter
'b'. This is useful only on systems which differentiate between
binary and text files (i.e. Windows. 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
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.
See also fclose,
fsockopen,
socket_set_timeout, and
popen.
fpassthruOutput all remaining data on a file pointerDescriptionintfpassthruintfp
Reads to EOF on the given file pointer from the current position 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. You may need to call
rewind to reset the file pointer to the beginning of
the file if you have already written data to the file. 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.
When using fpassthru on a binary file on Windows
systems, you should make sure to open the file in binary mode by
appending a b to the mode used in the call to
fopen.
See also readfile,
fopen, popen, and
fsockopenfputsWrites to a file pointerDescriptionintfputsintfpstringstrintlengthfputs 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 readDescriptionstringfreadintfpintlengthfread 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.
On systems which differentiate between binary and text files
(i.e. Windows) the file must be opened with 'b' included in
fopen mode parameter.
See also fwrite, fopen,
fsockopen, popen,
fgets, fgetss,
fscanf, file, and
fpassthru.
fscanfParses input from a file according to a formatDescriptionmixedfscanfinthandlestringformatstringvar1
The function fscanf is similar to
sscanf, but it takes its input from a file
associated with handle and interprets the
input according to the specified
format. If only two parameters were passed
to this function, the values parsed will be returned as an array.
Otherwise, if optional parameters are passed, the function will
return the number of assigned values. The optional parameters
must be passed by reference.
fscanf Exampleusers.txt
See also fread, fgets,
fgetss, sscanf,
printf, and sprintf.
fseekSeeks on a file pointerDescriptionintfseekintfpintoffsetintwhence
Sets the file position indicator for the file referenced by
fp.The new position, measured in bytes
from the beginning of the file, is obtained by adding
offset to the position specified by
whence, whose values are defined as
follows:
SEEK_SET - Set position equal to offset bytes.SEEK_CUR - Set position to current location plus offset.SEEK_END - Set position to end-of-file plus offset.
(To move to a position before the end-of-file, you need to pass a negative
value in offset.)If whence is not specified, it is assumed to be
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.
The whence argument was added after PHP 4.0.0.
See also ftell and
rewind.
fstatGets information about a file using an open file pointerDescriptionarrayfstatintfp
Gathers the statistics of the file opened by the file
pointer fp. This function is similar to the
stat function except that it operates
on an open file pointer instead of a filename.
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.
ftellTells file pointer read/write positionDescriptionintftellintfp
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.
ftruncateTruncates a file to a given lengthDescriptionintftruncateintfpintsize
Takes the filepointer, fp, and truncates the file to
length, size. This function returns &true; on
success and &false; on failure.
fwriteBinary-safe file writeDescriptionintfwriteintfpstringstringintlengthfwrite 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.
fwrite returns the number of bytes
written, or -1 on error.
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.
On systems which differentiate between binary and text files
(i.e. Windows) the file must be opened with 'b' included in
fopen mode parameter.
See also fread, fopen,
fsockopen, popen, and
fputs.
set_file_bufferSets file buffering on the given file pointerDescriptionintset_file_bufferintfpintbuffer
Output using fwrite is normally buffered at
8K. This means that if there are two processes wanting to write
to the same output stream (a file), each is paused after 8K of
data to allow the other to write. set_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. This ensures that all writes with
fwrite are completed before other processes
are allowed to write to that output stream.
The function returns 0 on success, or EOF if the request cannot
be honored.
The following example demonstrates how to use
set_file_buffer to create an unbuffered stream.
set_file_buffer example
See also fopen, fwrite.
is_dirTells whether the filename is a directoryDescriptionboolis_dirstringfilename
Returns &true; if the filename exists and is a directory.
The results of this function are cached. See
clearstatcache for more details.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
See also is_file and
is_link.
is_executableTells whether the filename is executableDescriptionboolis_executablestringfilename
Returns &true; if the filename exists and is executable.
The results of this function are cached. See
clearstatcache for more details.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
See also is_file and
is_link.
is_fileTells whether the filename is a regular fileDescriptionboolis_filestringfilename
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 linkDescriptionboolis_linkstringfilename
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,
is_file, and readlink.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
¬e.no-windows;
is_readableTells whether the filename is readableDescriptionboolis_readablestringfilename
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.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
See also is_writable.
is_writableTells whether the filename is writableDescriptionboolis_writablestringfilename
Returns &true; if the filename exists and is writable. 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.
This function will not work on remote files; the file to
be examined must be accessible via the server's filesystem.
See also is_readable.
is_writeableTells whether the filename is writableDescriptionboolis_writeablestringfilename
This is an alias for is_writableis_uploaded_fileTells whether the file was uploaded via HTTP POSTDescriptionboolis_uploaded_filestringfilename
Returns &true; if the file named by filename was
uploaded via HTTP POST. This is useful to help ensure that a
malicious user hasn't tried to trick the script into working on
files upon which it should not be working--for instance,
/etc/passwd.
This sort of check is especially important if there is any chance
that anything done with uploaded files could reveal their
contents to the user, or even to other users on the same
system.
is_uploaded_file is available only in
versions of PHP 3 after PHP 3.0.16, and in versions of PHP 4
after 4.0.2. If you are stuck using an earlier version, you can
use the following function to help protect yourself:
The following example will not work in
versions of PHP 4 after 4.0.2. It depends on internal
functionality of PHP which changed after that version.
]]>
See also move_uploaded_file, and the section
Handling file uploads
for a simple usage example.
linkCreate a hard linkDescriptionintlinkstringtargetstringlinklink creates a hard link.
See also the symlink to create soft links,
and readlink along with
linkinfo.
¬e.no-windows;
linkinfoGets information about a linkDescriptionintlinkinfostringpathlinkinfo 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.
¬e.no-windows;
mkdirMakes directoryDescriptionintmkdirstringpathnameintmode
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.
The mode is also modified by the current umask, which you
can change using umask.
&return.success;
See also rmdir.
move_uploaded_fileMoves an uploaded file to a new locationDescriptionboolmove_uploaded_filestringfilenamestringdestination
This function checks to ensure that the file designated by
filename is a valid upload file (meaning
that it was uploaded via PHP's HTTP POST upload mechanism). If
the file is valid, it will be moved to the filename given by
destination.
If filename is not a valid upload file,
then no action will occur, and
move_uploaded_file will return
&false;.
If filename is a valid upload file, but
cannot be moved for some reason, no action will occur, and
move_uploaded_file will return
&false;. Additionally, a warning will be issued.
This sort of check is especially important if there is any chance
that anything done with uploaded files could reveal their
contents to the user, or even to other users on the same
system.
¬e.sm.uidcheck;
move_uploaded_file is not affected by the normal
safe-mode UID-restrictions. This is not unsafe because
move_uploaded_file only operates on files uploaded
via PHP.
If the destination file already exists, it will be overwritten.
See also is_uploaded_file, and the section
Handling file uploads
for a simple usage example.
parse_ini_fileParse a configuration fileDescriptionarrayparse_ini_filestringfilenameboolprocess_sectionsparse_ini_file loads in the
ini file specified in filename,
and returns the settings in it in an associative array.
By setting the last process_sections
parameter to &true;, you get a multidimensional array, with
the section names and settings included. The default
for process_sections is &false;
This function has nothing to do with the
&php.ini; file. It is already processed,
the time you run your script. This function can be used to
read in your own application's configuration files.
The structure of the ini file is similar to that of
the &php.ini;'s.
Contents of sample.iniparse_ini_file example
]]>
Would produce:
1
[five] => 5
[path] => /usr/local/bin
)
Array
(
[first_section] => Array
(
[one] => 1
[five] => 5
)
[second_section] => Array
(
[path] => /usr/local/bin
)
)
]]>
pathinfoReturns information about a file pathDescriptionarraypathinfostringpathpathinfo returns an associative array
containing information about path. The
following array elements are returned:
dirname, basename
and extension.
pathinfo Example
]]>
Would produce:
See also dirname,
basename, parse_url
and realpath.
pcloseCloses process file pointerDescriptionintpcloseintfp
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.
popenOpens process file pointerDescriptionintpopenstringcommandstringmode
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;.
If the command to be executed could not be found, a valid
resource is returned. This may seem odd, but makes sense; it
allows you to access any error message returned by the shell:
&1', 'r');
echo "'$fp'; " . gettype($fp) . "\n";
$read = fread($fp, 2096);
echo $read;
pclose($fp);
?>
]]>
See also pclose.
readfileOutputs a fileDescriptionintreadfilestringfilenameintuse_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.
Versions prior to PHP 4.0.5 do not handle HTTP redirects. Because
of this, directories must include trailing slashes.
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.
readlinkReturns the target of a symbolic linkDescriptionstringreadlinkstringpathreadlink 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 is_link,
symlink, and
linkinfo.
¬e.no-windows;
renameRenames a fileDescriptionintrenamestringoldnamestringnewname
Attempts to rename oldname to
newname.
&return.success;
rewindRewind the position of a file pointerDescriptionintrewindintfp
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.
If you have opened the file in append ("a") mode, any data you write
to the file will always be appended, regardless of the file position.
See also fseek and
ftell.
rmdirRemoves directoryDescriptionboolrmdirstringdirname
Attempts to remove the directory named by dirname.
The directory must be empty, and the relevant permissions must permit this.
&return.success;
See also mkdir and unlink.
statGives information about a fileDescriptionarraystatstringfilename
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.
Returns &false; in case of error.
stat cannot be used on remote files.
The results of this function are cached. See
clearstatcache for more details.
lstatGives information about a file or symbolic linkDescriptionarraylstatstringfilename
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:
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.
lstat cannot be used on remote files.
The results of this function are cached. See
clearstatcache for more details.
realpathReturns canonicalized absolute pathnameDescriptionstringrealpathstringpathrealpath expands all symbolic links and
resolves references to '/./', '/../' and extra '/' characters in
the input path and return the canonicalized
absolute pathname. The resulting path will have no symbolic link,
'/./' or '/../' components.
realpath returns &false; on failure, e.g. if
the file does not exists.
realpath examplesymlinkCreates a symbolic linkDescriptionintsymlinkstringtargetstringlinksymlink 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.
¬e.no-windows;
tempnamCreate file with unique file nameDescriptionstringtempnamstringdirstringprefix
Creates a file with a unique filename in the specified directory.
If the directory does not exist, tempnam may
generate a file in the system's temporary directory, and return
the name of that.
Prior to PHP 4.0.6, the behaviour of the
tempnam function was 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 &false; string on
failure.
tempnam example
This function's behavior changed in 4.0.3. The temporary file is also
created to avoid a race condition where the file might appear in the
filesystem between the time the string was generated and before the
the script gets around to creating the file. Note, that you need
to remove the file in case you need it no more, it is not done
automatically.
See also tmpfile and unlink.
tmpfileCreates a temporary fileDescriptioninttmpfile
Creates a temporary file with an unique name in write mode,
returning a file handle similar to the one returned by
fopen.
The file is automatically removed when closed (using
fclose), or when the script ends.
For details, consult your system documentation on the
tmpfile(3) function, as well as the
stdio.h header file.
tmpfile example
See also tempnam.
touchSets access and modification time of fileDescriptioninttouchstringfilenameinttime
Attempts to set the access and 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. This is equivalent to what utime
(sometimes referred to as utimes) does.
If the file does not exist, it is created.
&return.success;
touch exampleumaskChanges the current umaskDescriptionintumaskintmaskumask 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.
¬e.no-windows;
unlinkDeletes a fileDescriptionintunlinkstringfilename
Deletes filename. Similar to the Unix C
unlink() function.
&return.success;
See also rmdir for removing directories.