WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 File Handling


The fopen () function is used to open a file in PHP.


Open file

The

fopen () function is used to open a file in PHP.

The first parameter 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 be opened in the following modes:

mode description
r Read-only. Start at the beginning of the file.
r + Read /write. Start at the beginning of the file.
w Write only. 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 contents of the file by writing to the end of the file.
x Write only. Create a new file. If the file already exists, FALSE and an error are returned.
x + Read /write. Create a new file. If the file already exists, FALSE and an error are returned.

Note: If the fopen () function cannot open the specified file, returns 0 (false).

Example

If the fopen () function cannot open the specified file, the following example generates a message:

<html>
<body>

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>

</body>
</html>


Close the file

fclose () function is used to close the open file:

<?php
$file = fopen("test.txt","r");

//execute some code

fclose ($ file);
?>


End of file detection (EOF)

The

feof () function detects whether the end of file (EOF) has been reached.

The feof () function is useful when looping through data of unknown length.

Note: You cannot read open files in w, a, and x modes!

if (feof ($ file)) echo "end of file";


Read files line by line

The

fgets () function is used to read a file line by line from a file.

Note: After calling this function, the file pointer moves to the next line.

Example

The following example reads the file line by line until the end of the file:

<?php
$ file = fopen ("welcome.txt", "r") or exit ("Cannot open file!");
//read each line of the file until the end of the file
while(!feof($file))
{
    echo fgets($file). "<br>";
}
fclose($file);
?>


Read file character by character

The fgetc () function is used to read a file character by character from a file.

Note: After calling this function, the file pointer moves to the next character.

Example

The following example reads the file character by character until the end of the file:

<?php
$file=fopen("welcome.txt","r") or exit("Cannot open file!");
while (!feof($file))
{
    echo fgetc($file);
}
fclose($file);
?>