May 11, 2021 PHP
The fopen() function is used to open a file in PHP.
The fopen() function is used to open a file in PHP.
The first argument of this function contains the name of the file to be opened, and the second parameter specifies which mode to use to open the file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
The file may open in the following modes:
model | describe |
---|---|
r | Read only.Start in the beginning of the file. |
r+ | Read / write.Start in the beginning of the file. |
w | just write.Open and empty the contents of the file; if the file does not exist, create a new file. |
w+ | Read / write.Open and empty the contents of the file; if the file does not exist, create a new file. |
a | Append.Open and write to the end of the file. If the file does not exist, create a new file. |
a+ | Read / append.Keep the file content by writing content to the end of the file. |
x | just write.Create a new file.Returns false and an error if the file already exists. |
x+ | Read / write.Create a new file.Returns false and an error if the file already exists. |
Note: If the fopen() function cannot open the specified file, 0 (false) is returned.
If the fopen() function cannot open the specified file, the following instance generates a message:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
The fclose() function is used to close open files:
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
The feof() function detects whether the end of the file (EOF) has been reached.
Feof() functions are useful when looping through data of unknown lengths.
Note: In w, a, and x modes, you cannot read open files!
if (feof($file)) echo "End of file";
The fgets() function is used to read the file line by line from the file.
Note: After the function is called, the file pointer moves to the next line.
The following example reads the file line by line until the end of the file:
<?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);
?>
The fgetc() function is used to read the file character by character from the file.
Note: After the function is called, the file pointer moves to the next character.
The following example reads the file character by character until the end of the file:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
To view the full reference manual for PHP file system functions, please visit our PHP Filesystem reference manual.
In the next section, we'll look at the upload of PHP files.