fopen

(PHP 3, PHP 4 )

fopen -- Opens file or URL

Description

int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

fopen() binds a named resource, specified by filename, to a stream. If filename is of the form "scheme://...", it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled safe_mode, or open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note: The list of supported protocols can be found in Appendix I.

mode specifies the type of access you require to the stream. It may be any of the following:

Note: 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 are encouraged to include the 'b' flag in order to make your scripts more portable.

The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too.

The optional fourth zcontext is used for specifying tuning parameters and callbacks.

If the open fails, the function returns FALSE.

Example 1. fopen() example

<?php
$fp = fopen ("/home/rasmus/file.txt", "r");
$fp = fopen ("/home/rasmus/file.gif", "wb");
$fp = fopen ("http://www.example.com/", "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.

<?php
$fp = fopen ("c:\\data\\info.txt", "r");
?>

See also Appendix I, fclose(), fgets(), fsockopen(), file(), file_exists(), is_readable(), socket_set_timeout(), and popen().