HOME HTML EDITOR C JAVA PHP

PHP File Handling

File handling is an important part of any web application. PHP has several functions for creating, reading, uploading, and editing files.

Warning: Be careful when manipulating files. You can do a lot of damage if you make a mistake (e.g., accidentally overwriting a critical system file).

1. The readfile() Function

The readfile() function is the simplest way to read a file and write it to the output buffer.

<?php
  echo readfile("webdictionary.txt");
?>

2. Open, Read, and Close Files

For better control, we use fopen(), fread(), and fclose().

Opening a File: fopen()

The first parameter contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened.

<?php
  $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
  echo fread($myfile, filesize("webdictionary.txt"));
  fclose($myfile);
?>

3. File Modes

Common modes used in fopen():

4. Reading a Single Line: fgets()

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

<?php
  $myfile = fopen("webdictionary.txt", "r");
  echo fgets($myfile);
  fclose($myfile);
?>

5. Check End-of-File: feof()

The feof() function checks if the "end-of-file" (EOF) has been reached. This is useful for looping through data of unknown length.

<?php
  $myfile = fopen("webdictionary.txt", "r");
  while(!feof($myfile)) {
    echo fgets($myfile) . "<br>";
  }
  fclose($myfile);
?>
Best Practice: Always use fclose() after you are done with a file. It is good programming practice to not leave open files running on your server, as they consume resources.