File Access
Functions
$handle = fopen( FILENAME, FILEMODE
)
FILEMODE:
'r' read r
'r+' write r/w
'w' overwrite w
'w+' overwrite r/w
'a' append w
'a+' append r/w
- For binary files, include 'b' in the
file mode (i.e. "rb",
"wb") (not needed in Unix, but helpful for portability).
$bool = fclose( $handle )
$str = fread( $handle, LENGTH )
$int = fwrite( $handle, $string [,
LENGTH] )
- Return value; FALSE: error; Else:
number of bytes written.
$int = fseek( $handle, OFFSET [,
RELATIVE_TO = SEEK_SET] )
RELATIVE_TO: SEEK_SET,
SEEK_CUR,
SEEK_END
- Return value; 0: success, -1: failure.
$bool = feof( $handle )
$int = ftell( $handle )
$int rewind ( $handle )
$bool = ftruncate( $handle, LENGTH )
$array = file( FILENAME )
$string = file_get_contents(
FILENAME
)
$int = file_put_contents( FILENAME,
$string [, FILE_APPEND]
)
$string = fgetc( $handle)
$string = fgets( $handle [, LENGTH
=
1024])
- Returns FALSE if error.
- Stops reading at newline (included in
return value) or EOF.
$array = fscanf( $handle,
FORMAT_STR )
$num_vars = fscanf( $handle,
FORMAT_STR
[, $var]+ )
$filename = basename( $fullname [,
$suffix_to_remove] )
$path = dirname( $fullname )
$path_array = pathinfo( $fullname
)
$abs_fullname = realpath(
$rel_fullname
)
copy, mkdir, rename,
rmdir, unlink , symlink
file_exists, is_dir,
is_executable,
is_file, is_link,
is_readable, is_writable
filesize, filetype,
disk_free_space
URL wrappers
- Doesn't allow existing files to be
overwritten.
- If
allow_url_fopen is
enabled in php.ini, HTTP and FTP URLs
can be used with most of the functions that take a filename as a
parameter (as of PHP 4.0.4); prior to that, the following option had to
be configured: -enable-url-fopen-wrapper.
- You can also write to files on an FTP
server (provided that
you have connected as a user with the correct access rights). You can
only create new files using this method; if you try to overwrite a file
that already exists, the
fopen() call will fail.
- To connect as a user other than
'anonymous', you need to
specify the username (and possibly password) within the URL, such as
'ftp://user:password@ftp.example.com/path/to/file'. (You can use the
same sort of syntax to access files via HTTP when they require Basic
authentication.)
<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
echo "<p>Unable to open remote file for writing.\n";
exit;
}
// Write the data here.
fputs ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>