PHP File Handling

0
2500

Today we are going to learn all the basics of how to open, create, read and write the file in this PHP File Handling tutorial.

  • File handling in PHP is mostly similar to file handling in standard C language.
  • PHP provides various tools for creating, uploading and editing files.
  • You need to be very careful while dealing with files, because you can harm the file data if something goes wrong.
  • Any information written in the file is temporarily written in the buffer and is then later stored on the hard-disk when the file is saved.
  • Opposed to it, if we want to read the saved file data, it is first brought from the hard-disk to the buffer and is then read from buffer.
  • To work with any file either you have to create it if it doesn’t exist or you have to open it if it exists.
  • The function fopen() is used to open an existing file and create a new file if it does not exist.
  • But the function fopen() requires the mode in which the file is to be opened.
  • Mode of a file is the task assigned to the file that it should do.
  • The modes of file in PHP are given below:
  • Mode Description
    r Read only mode, with the file pointer at the start of the file.
    r+ Read/Write mode, with the file pointer at the start of the file.
    w Write only mode. Truncates the existing file by overwriting it. If file doesn’t exist the fopen() function creates a new file.
    w+ Read/Write mode. Truncates the existing file by overwriting it. If file doesn’t exist the fopen() function creates a new file.
    a Append mode, with the file pointer at the end of the file. If the file doesn’t exist, the fopen() function creates a new file.
    a+ Read/Append mode, with the file pointer at the end of the file. If the file doesn’t exist, the fopen() function creates a new file.
    x Create and open for writing only. If the file exists already, it returns FALSE and generates an error. If file doesn’t exist, a new file is created.
    x+ Create and open for reading and writing. If the file exists already, it returns FALSE and generates an error. If file doesn’t exist, a new file is created.

    table 1

  • So let us go through different functions to manipulate file:
  1. Opening a file (fopen()):
    • To work with a file we need to create it first if it doesn’t exist or open it first, if it exists.
    • The function fopen() is used to open a file if it exists or it creates a file if it doesn’t exist.
    • Syntax of fopen() function:
    • The fopen() function takes 2 parameters,
    • First is the name of the file with which we want to work.
    • Second is the mode with which we want to open the file.
    • We know whatever we read from or write to the file is present in the buffer. The file data in this buffer is pointed by the file pointer which helps us to read from and write to the buffer/file.
    • The fopen() function returns the file pointer when it successfully creates a new file or opens an existing file or else returns 0 (zero) if it fails to do so.
    • This pointer moves ahead as we read from or write to the file pointing the respective location of the file data.
    • Let us see an example that creates a new file using fopen() function.
    • To demonstrate it, create a new folder named file_handling in the htdocs folder in xampp folder in C drive. Then open a new notepad++ document and save it as index.php in this newly created file_handling folder.
    • The code is given below:
    • Here, just see the PHP code inside php tag. We have used a fopen function with a file name one.txt and the write file mode i.e. “w” as shown below:
    • This file will be pointed by $fp file pointer i.e. the file pointer returned by fopen() function will be assigned to $fp.
    • In this case if one.txt exists, it will be opened in write mode i.e. all its data will be truncated and overwritten.
    • If one.txt doesn’t exist, a new file named one.txt will be created with write mode i.e. we are allowed only to write to the file, not to read.
    • We know if the fopen() function fails to create a file or open a file, it returns 0 (zero).
    • Hence we check $fp in the if statement as shown
    • If 1 (true) has been returned i.e. the one.txt file has been created successfully, it will display the sentence File one.txt has been created successfully otherwise nothing.
    • Now open the browser and write localhost/file_handling in its address bar and see the output shown below:
    • fopen_function_output
      fig 1

    • This new file one.txt is created in the file_handling folder on our localhost server as shown below:
    • one_txt_file_created
      fig 2

    • To read a file we need to open an existing file in read mode i.e. “r” as shown below:
    • All the other modes like a, a+, r+, w+, x, x+ can be used in the same fashion according to their use.
  2. Closing a file (fclose()):
    • Any file that is opened needs to be closed every time.
    • The function fclose() is used to close an open file.
    • Syntax of fclose() function:
    • The fclose() function has the file pointer of the file to be closed as its parameter.
    • The function fclose() has to be used with the conjunction of fopen() function.
    • The function fclose() returns true if the file is successfully closed or else it returns false, if the file is not closed due to some problem.
    • Let us see an example of fclose() function:
    • Here, we are creating a file two.txt using fopen() function and closing the file using fclose() function.
    • $fp is the file pointer pointing to the file two.txt. So the statement
      is used to close the file.
    • As the fclose() function returns true on success and false on failure, we have checked it in the if statement and displayed the statement accordingly.
    • The output is shown below:
    • two_txt_file_closed
      fig 3

      Next after understanding the task of opening and closing the file, we should now know how to read an existing file.
      But before that it is very important to know the end of file so that we can stop reading when we reach the end of file.
      End of file is reached where the information written in the file is finished.

  3. Checking end of file (feof()):
    • It is very important that we know the End-Of-File (EOF) while reading it.
    • The function feof() is the file end of file function.
    • It returns true if the end of file has reached and false if end of file has not yet reached.
    • We can read the whole file data of unknown length with the use of this feof() function.
    • Syntax of feof() function:
    • It has the file pointer of the file whose end has to be checked.
    • It is mostly used in while loop or if statement to check if end of file has been reached or not during reading the file.
    • Example is given below:
    • Here, if the file pointed by $fp has not reached its end, it will return false. This will be negated using not operator (!) and made true to execute the code in the while loop. Because we want to read the file data when it has not reached its end.
    • When the file reaches its end, the feof() function will return true. Now as file has reached its end, we want to stop reading.
    • This is done again by negating true and making it false using not operator (!). As true has been converted to false, the control will not execute the while loop code because the condition of while loop has become false.
  4. Reading a file line by line (fgets()):
    • Now with feof() function we are ready to read the whole file.
    • The file can be read line by line i.e. one line at a time using fgets() function.
    • Syntax of fgets() function:
    • After reading one line the file pointer points to the next line, thus reading line by line.
    • Let us read a file info.txt which is present in our file_handling folder line by line:
    • The code for reading the file is given below:
    • Here, in the above code we have opened the existing file using fopen() function. If any problem occurs in opening the file, an error message will be displayed otherwise the file will be read and its data will be displayed successfully.
    • While reading the file, the file pointer is checked to see whether its end of file (EOF) has reached or not.
    • If the EOF has not reached one line of the file info.txt file is read using fgets() function and stored in $str variable. This read line is then displayed on the page using echo function.
    • This process continues till the feof() function returns false. Once the feof() function returns value true, it means it has reached its end and the reading process stops.
    • The file is then closed using fclose() function.
    • The output of the read data is shown below:
    • reading_file_line_by_line_with_fgets
      fig 4

  5. Reading a file character by character (fgetc()):
    • As we have seen reading a file line by line, we can even read a file character by character.
    • Reading a file character by character means reading one character at one time.
    • This is achieved using fgetc() function. Syntax is as follows:
    • Here, after reading one character the file pointer points to the next character.
    • Let us see an example of fgetc() function.
    • The code is given below:
    • Here, we have used the same logic that was used while demonstrating fgets() function.
    • The only difference is that we have used fgetc() function to read the file data and removed html break tag from the echo statement. Because in this case we are reading character by character; so if break tag is kept as it is, it will give line break after every character.
    • The output is shown below:
    • reading_file_char_by_char_with_fgetc
      fig 5

Thus today we learned some basics of file handling in this PHP File handling tutorial.

LEAVE A REPLY

Please enter your comment!
Please enter your name here