PHP File

Use the fopen() function to open files in PHP. The first parameter of this function is the file to be opened and the second parameter specifies in which mode the file should be opened:
1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
 
<body>
 
<?php
 
$file=fopen("welcome.txt","r");
 
?>
 
</body>
 
</html>
The modes in which the file can be opened are listed below:
Modes Description
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 clears the contents of file; or creates a new file if it doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+ Read/Append. 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
Note that if the fopen() function is unable to open the specified file, it returns 0 (false).
To close an open file use the fclose() function:
1
2
3
4
5
6
7
8
9
<?php
 
$file = fopen("test.txt","r");
 
//some code to be executed
 
fclose($file);
 
?>
To check if the "end-of-file" (EOF) has been reached use the feof() function.
To loop through data of unknown length use the feof() function.
Note that you cannot read from files opened in w, a, and x mode!
To read a single line from a file use the fgets() function.
Note that after a call to this function the file pointer has moved to the next line.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
 
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
 
//Output a line of the file until the end is reached
 
while(!feof($file))
 
  {
 
  echo fgets($file). "<br />";
 
  }
 
fclose($file);
 
?>
AJAX Live Search
PHP ODBC
PHP Include
PHP Sessions