289 of 410 menu

The fopen Function

The fopen function opens a file or URL and returns a pointer to the resource. The first parameter of the function is the path to the file or URL, the second parameter is the opening mode. Returns a file pointer on success, false on error.

Syntax

fopen(filename, mode, [use_include_path], [context]);

Example

Open a file for reading:

<?php $res = fopen('file.txt', 'r'); var_dump($res); ?>

Code execution result:

resource(5) of type (stream)

Example

Open a file for writing (if the file does not exist, it will be created):

<?php $res = fopen('newfile.txt', 'w'); var_dump($res); ?>

Code execution result:

resource(5) of type (stream)

Example

Try to open a non-existent file for reading:

<?php $res = fopen('nonexistent.txt', 'r'); var_dump($res); ?>

Code execution result:

false

Example

Open a URL for reading:

<?php $res = fopen('https://example.com', 'r'); var_dump($res); ?>

Code execution result:

resource(5) of type (stream)

See Also

  • the fclose function,
    which closes a file
  • the fread function,
    which reads from a file
  • the fwrite function,
    which writes to a file
byenru