How to use fopen() function in PHP?

The fopen() function in PHP is an inbuilt function which is used to open a file or an URL.

1. Code:

 <?php
 
$file = fopen("D:\soltuts.txt", "r");

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

fclose($file);
?> 

2. Definition and Usage:

fopen(filename, mode, include_path, context)

ParameterDescription
filenameRequired. Specifies the file or URL to open
modeRequired. Specifies the type of access you require to the file/stream.Possible values: “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_pathOptional. Set this parameter to ‘1’ if you want to search for the file in the include_path (in php.ini) as well
contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

3. Example:

Input:

File: soltuts.txt

Output:

Soltuts.com is providing PHP tutorials, tips, tricks and code snippets.
All published articles are simple and easy to understand, tested on our development environment.