Contents / Previous / Next


File IO and Filesystem Functions

Open and Close

The most versatile file IO (input and output) function to open file or URL is: int fopen(string filename, string mode [, int use_include_path]) Return value = File pointer: The returned integer is called a file reference or file pointer. It is zero if the operation failed (e.g., because the file did not exist).

filename: If filename begins with "http://" (not case sensitive), an HTTP connection is opened to the specified server, the page is requested using the HTTP GET method.
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.
If filename is one of "php://stdin", "php://stdout", or "php://stderr", the corresponding stdio stream will be opened.
If filename begins with anything else, the file will be opened from the filesystem.

mode may be any of the following (read, write or append):

If the final optional parameter use_include_path is set to true (or 1) an attempt will be made to find the file in the directories specified by PHP's include path.

Examples:

$fp = fopen ("/home/rasmus/file.txt", "r"); $fp = fopen ("/home/rasmus/file.gif", "wb"); $fp = fopen ("http://www.php.net/", "r"); $fp = fopen ("ftp://user:password@example.com/", "w"); Note: In order for a file to be accessed or created, the directory and/or file in question must have the appropriate permissions.
Access must be granted to the user under which the PHP script will be executed (usually the same username as the web server).

Close: Although all file references are automatically closed upon the termination of the PHP script which opened them, it is good programming practice to close the files manually with fclose():

bool fclose (int fp) Closes an open file pointer fp and returns TRUE on success and FALSE on failure.

Example (open and close a file test.txt in /tmp/):

<? $fp = fopen('/tmp/test.txt', 'a+'); if(!$fp) { echo "Error! Couldn't open the file."; } else { // $fp now can be used for I/O } if(!fclose($fp)) { echo "Error! Couldn't close the file."; } ?>

Functions Related File Opening:

int fflush (int fp): Forces a write of all buffered output

int popen (string command, string mode): Opens a pipe to a process executed by forking the command. Example:

$fp = popen ("/bin/ls", "r"); 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().

int fsockopen (string [udp://]hostname, int port [, int errno [, string errstr [, double timeout]]])
Open Internet or Unix domain socket connection.

bool flock (int fp, int operation [, int wouldblock])
Locks a file.


Read

There are many different methods to read and write data, one of the most basic methods is the fgets() function: string fgets (int fp, int length) It gets a line from an open file pointed to by fp.
fgets 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, it returns FALSE.

Example:

<? $fp = fopen('/tmp/test.txt', 'r+'); if(!$fp) { echo "Error! Couldn't open the file."; } else { while (!feof ($fp)) { $buffer = fgets($fp, 4096); echo "$buffer<BR>"; } } if(!fclose($fp)) { echo "Error! Couldn't close the file."; } ?>

The fread functions allows (binary-safe) file read of blocks of bytes:

string fread (int fp, int length) It 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.

string fgetc (int fp): Gets character from file pointer.
It returns a string containing a single character and returns FALSE on EOF.

mixed fscanf (int fp, string format [, string var1...]): Is a C-style function, it parses input from a file according to a format.


Write

The complement of fgets() and fread() is fwrite() and fputs() which is an alias to fwrite():

int fwrite (int fp, string string [, int length]) fwrite() 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. Example: <? $fp = fopen('/tmp/me.txt', 'w'); fwrite( $fp, "its me again!\n" ); fclose($fp); ?>


Moving the File Position Indicator

The file position indicator is a marker used by PHP to keep track of where the currently executing file operations take place.
It can be used for accessing a specific location within a file.

The fseek function sets the file position indicator for the file referenced by fp:

int fseek (int fp, int offset [, int whence]) The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by the whence parameter, whose values are defined as follows:
SEEK_SET - Set position equal to offset bytes (default),
           (measure from the beginning of the file).
SEEK_CUR - Set position to current location plus offset.
SEEK_END - Set position to end-of-file plus offset.
Upon success, returns 0; otherwise, returns -1.
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.

int ftell (int fp): Returns the position of the file pointer referenced by fp; i.e., its offset from the beginning of the file.

int rewind (int fp): Sets the file position indicator for fp to the beginning of the file.

int feof (int fp): Returns TRUE if the file pointer is at EOF or an error occurs; otherwise returns FALSE.

Example:

<? $fp = fopen( "/tmp/test.txt", 'r' ); fseek( $fp, rand( 1, 64 ) ); $offset = ftell( $fp ); $value = fread( $fp, 1 ); echo "We randomly landed at $offset and read the byte: $value<BR>"; ?>


Reading a File directly into Array or String

The file() function reads entire file into an array: array file (string filename [, int use_include_path]) 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.
Example (read a web page into an array and print it out): $fcontents = file ('http://localhost'); while (list ($line_num, $line) = each ($fcontents)) { echo "<b>Line $line_num:</b> " . htmlspecialchars ($line) . "<br>\n"; }
Example (read a web page into an array and join it to a string): $fcontents = join ('', file ('http://localhost'));

stringfile_get_contents (string filename [, int use_include_path [, resource context]]):
Reads entire file into a string.
It is identical to file(), except that file_get_contents() returns the file in a string. Note: This function is binary-safe. (See example in section "Binary Data").

int file_put_contents ( string filename, string data [, int flags [, resource context]]) :
Writes a string to a file. flags can take FILE_USE_INCLUDE_PATH and/or FILE_APPEND. Note: This function is binary-safe. (See example in section "Binary Data").


Binary Data

string pack ( string format [, mixed args]):
Packs data into binary string.
It packs the given arguments into binary string according to format and returns it.
The idea to this function was taken from Perl and all formatting codes work the same (some are missing such as Perl's "u").
Currently implemented are:

a NUL-padded string
A SPACE-padded string
h Hex string, low nibble first
H Hex string, high nibble first
c signed char
C unsigned char
s signed short (always 16 bit, machine byte order)
S unsigned short (always 16 bit, machine byte order)
n unsigned short (always 16 bit, big endian byte order)
v unsigned short (always 16 bit, little endian byte order)
i signed integer (machine dependent size and byte order)
I unsigned integer (machine dependent size and byte order)
l signed long (always 32 bit, machine byte order)
L unsigned long (always 32 bit, machine byte order)
N unsigned long (always 32 bit, big endian byte order)
V unsigned long (always 32 bit, little endian byte order)
f float (machine dependent size and representation)
d double (machine dependent size and representation)
x NUL byte
X Back up one byte
@ NUL-fill to absolute position
The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.

Example:

$binarydata = pack ("nvc*", 0x1234, 0x5678, 65, 66); The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

array unpack ( string format, string data):
Unpacks from binary string into array according to format. Returns array containing unpacked elements of binary string. Example:

<? $out_bin_str = pack ("nvc*", 0x1234, 0x5678, 65, 66); if ( file_put_contents ( "bin.dat", $out_bin_str) ) { exit( "Error!<BR>\n" ); } $in_bin_str = file_get_contents( "bin.dat" ); $bin_array = unpack ( "nvc*", $in_bin_str ); print_r ( $bin_array ); ?>

Comments and Notes on Binary Data: An alternative to binary data storage are "bzip2ed" ASCII-data-files.

PHP offers a lot of support for transfering binary images.

Note:
On systems running PHP which differentiate between binary and text files (such as Windows), you'll need to open the file in binary mode by including "b" along with any other modes that you may require (e.g.,"rb").

Note:
If you have "magic quotes" enabled, fread() may not function as expected (especially when dealing with a null character). PHP will automatically convert the "null" character to its escaped version \0 in the resulting input. Toggling "magic quotes" can be done by using the set_magic_quotes_runtime() and get_magic_quotes_runtime() functions.


Tests and Info on Files

bool file_exists (string filename): Checks whether a file exists (will not work on remote files).

int filesize (string filename): Returns the size of the file (will not work on remote files).

Other file-info functions (see manual for more info):

stat     : Gives information about a file
realpath : Returns canonicalized absolute pathname
pathinfo : Returns information about a file path

linkinfo : Gets information about a link
readlink : Returns the target of a symbolic link

filetype  : Gets file type
fileatime : Gets last access time of file
filectime : Gets inode change time of file
fileinode : Gets file inode

filegroup : Gets file group
filemtime : Gets file modification time
fileowner : Gets file owner
fileperms : Gets file permissions

is_dir        : Tells if filename is a directory
is_executable : Tells if filename is executable
is_file       : Tells if filename is a regular file
is_link       : Tells if filename is a symbolic link
is_readable   : Tells if filename is readable
is_writable   : Tells if filename is writable
is_writeable  : Tells if filename is writable

diskfreespace    : Returns available space in directory
disk_total_space : Returns the total size of a directory


Change File Permissions

int chmod (string filename, int mode): Changes file mode (permissions).
mode an octal value prefixed with a zero (0). Example:
chmod ("/somedir/somefile", 0755); 

int chown (string filename, mixed user): Changes the file owner.

int chgrp (string filename, mixed group): Changes the file group.


Filesystem Operations

int copy (string source, string dest): Makes a copy of a file. Returns TRUE if the copy succeeded.

int rename (string oldname, string newname): Attempts to rename oldname to newname and returns TRUE on success.

int mkdir (string pathname, int mode): Attempts to create the directory specified by pathname.

int unlink (string filename): Deletes filename. Similar to the Unix C unlink() function. Returns 0 or FALSE on an error.

int rmdir ( string dirname): Attempts to remove the directory named by dirname. The directory must be empty.

Other filesystem functions (see manual for more info):

link     : Create a hard link
symlink  : Creates a symbolic link
tempnam  : Creates unique file name
tmpfile  : Creates a temporary file
touch    : Sets modification time of file


Working with Directories

The following directory functions are available:
dirname(), 
is_dir(), 
mkdir(),
rmdir()   : see the Filesystem section.

getcwd    : gets the current working directory
chdir     : Change directory
chroot    : Change the root directory
opendir   : open directory handle
closedir  : close directory handle
readdir   : read entry from directory handle
rewinddir : rewind directory handle

dir       : directory class

There exists also a directory class called dir, a pseudo-object oriented mechanism for reading a directory.


MISC Convenience Functions

string basename (string path [, string suffix]): Returns filename component of path.
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.

string dirname (string path): Returns directory name component of path.