File processing...LOGIN

File processing for beginners in PHP

File processing

fopen() function is used to open files in PHP

The first parameter of the function contains the file to be opened The name of the file. The second parameter specifies which mode to use to open the file. welcome.txt","r");

?>

</body>
</html>



The file may be generated through the following patterns Open

r Read-only. Start at the beginning of the file. ​ r+ ​ Read/write. Start at the beginning of the file. ​

  w   Only write. Opens and clears the contents of the file; if the file does not exist, creates a new file. ​

​ w+ ​ Read/Write. Opens and clears the contents of the file; if the file does not exist, creates a new file. ​

​ a ​ append. Opens and writes to the end of the file, or creates a new file if it does not exist. ​

​ a+ ​ Read/Append. Maintain file contents by writing to the end of the file.

x Write only. Create new file. If the file already exists, returns FALSE and an error.

x+ Read/write. Create new file. If the file already exists, returns FALSE and an error.

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

Close the file

The fclose() function is used to close the open file: <?php $file = fopen("test.txt","r");

//Execute some code

fclose($file);

?>

Detecting the end of file (EOF)

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: In w , a and x modes, you cannot read open files!

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

##Read the file line by line

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

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

<?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 the file character by character

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

Note: After calling this function, the file pointer will move to the next character

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


Next Section
<?php echo "hello world"; ?>
submitReset Code
ChapterCourseware