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

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

Example

Open a file for reading:

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

Code execution result:

phpresource(5) of type (stream)

Example

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

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

Code execution result:

phpresource(5) of type (stream)

Example

Try to open a non-existent file for reading:

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

Code execution result:

phpfalse

Example

Open a URL for reading:

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

Code execution result:

phpresource(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