Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

fopen()

Example

Read the lines in the opened file until the end of the file (EOF) is reached.

<?php
$file = fopen(“test.txt”“r”);

//Output lines until EOF is reached
while(! feof($file)) {
  $line = fgets($file);
  echo $line. “<br>”;
}

fclose($file);
?>

Definition and Usage

The fopen() function opens a file or URL.

 

Note: When writing to a text file, be sure to use the correct line-ending character! Unix systems use \n, Windows systems use \r\n, and Macintosh systems use \r as the line ending character. Windows offers a translation flag (‘t’) which will translate \n to \r\n when working with the file. You can also use ‘b’ to force binary mode. To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.rephrase

Syntax

fopen(filenamemodeinclude_pathcontext)

Parameter Values

 

Parameter

Description

filename

Essential. To open a file or URL, specify it.

mode

Essential. Indicates the kind of file/stream access you need.
Potential amounts

  • “r” – Read only. Starts at the beginning of the file
  • “r+” – Read/Write. Starts at the beginning of the file
  • “w” – Write only. Opens and truncates the file; or creates a new file if it doesn’t exist. Place file pointer at the beginning of the file
  • “w+” – Read/Write. Opens and truncates the file; or creates a new file if it doesn’t exist. Place file pointer at the beginning of the file
  • “a” – Write only. Opens and writes to the end of the file or creates a new file if it doesn’t exist
  • “a+” – Read/Write. Preserves file content by writing to the end of the file
  • “x” – Write only. Creates a new file. Returns FALSE and an error if file already exists
  • “x+” – Read/Write. Creates a new file. Returns FALSE and an error if file already exists
  • “c” – Write only. Opens the file; or creates a new file if it doesn’t exist. Place file pointer at the beginning of the file
  • “c+” – Read/Write. Opens the file; or creates a new file if it doesn’t exist. Place file pointer at the beginning of the file
  • “e” – Only available in PHP compiled on POSIX.1-2008 conform systems.

include_path

Not required. If you also wish to search for the file in the include_path (in php.ini), set this option to ‘1’.

context

Not required. Indicates the file handle’s context. Context is a collection of parameters that can change how a stream behaves.

Technical Details

Return Value:

When something goes wrong, FALSE, a file pointer resource, and an error occur. By using a “@” in front of the function name, you can conceal the error.

PHP Version:

4.3+

PHP Changelog:

PHP 7.1: “e” option added
PHP 5.2: “c” and “c+” options were added.