Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Opening A File
3.
Reading A File
4.
Reading file With fread()
5.
Reading A Single Line
6.
Reading A Single Character
7.
Checking End Of File
8.
Writing To A File
9.
PHP Overwriting
10.
Closing A File
11.
PHP file upload
12.
Adding Restrictions
13.
FAQs
14.
Key Takeaways
Last Updated: Mar 27, 2024

PHP File Handling

Author Ranjul Arumadi
2 upvotes

Introduction

Storing data in files using a program is known as file handling. File handling is a crucial component of any application. We might need to open and process files to carry out specific tasks in our application. File handling in PHP is very similar to file handling in other programming languages like C. 

 

PHP file handling is done with the help of certain functions, which we will be discussing in this article. The PHP file handling functions are used for creating, reading, uploading, and editing files.

Opening A File

We could also use another method to open files. We could open files with the help of the fopen() function. We could also create a file with the help of the fopen() function. This is a better alternative as it gives more options than the readfile() function.

 

The fopen() function parameters are as follows: 

  • The first parameter mentions the file's name to be opened.
  • The second parameter mentions the mode in which we should open the file. 

 

The different modes in which we could open files are:

  • r   - Open a file in read-only mode. The file pointer will be at the beginning of the file.
  • w  - Open a file in write-only mode. If the file with that filename already exists, it will clear the file's contents. If the file with that filename does not exist already, it creates a new file. The file pointer will point to the beginning of the file.
  • a - Open a file in write-only mode. The existing data in the file is preserved. If the file doesn’t exist, we will create a new file. In write-only mode, the file pointer will point to the end of the file.
  • x - Creates a new file for write-only. If the file already exists, it will return FALSE and an error.
  • r+ - Opens a file for read/write. When using this mode to open a file, the file pointer points to the beginning of the file.
  • w+ -  Opens a file for read/write. If the file already exists, the contents of the file are erased. Otherwise, we will create a new file.  In read/write mode, the file pointer will point to the beginning of the file.
  • a+ - Opens a file for read/write. If the file already exists, we will preserve the file's contents. Otherwise, we will create a new file. The file pointer starts at the end of the file.
  • x+ - Creates a new file for read/write. If the file already exists, it returns FALSE and an error.

 

Consider the same file we used before, i.e., "demo.txt”. This program also displays an error msg if the file opening function is unsuccessful.

 

Program

<?php
$file = fopen("demo.txt", "r") or die("File not opened");
fclose($file);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Let us see what happens if the required file is not present.

 

Program

<?php
$file = fopen("Notdemo.txt", "r") or die("File not opened");
fclose($file);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Reading A File

File handling in PHP is mainly enforced using a function to read files. A file can be read in PHP using the readfile() function. This function reads a file and writes it to the output buffer. Let us consider the following example.

 

We have saved a text file called"demo.txt" stored on the server. We use the readfile() function to read the contents of"demo.txt" and write it to the output buffer. On success, it also returns the number of bytes of that file.

 

Contents of the file:

 

Program

<?php
echo readfile("demo.txt");
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output

Reading file With fread()

Once a file is opened, we could use the fread() function to read the contents of that file. This function accepts two arguments as its parameters. The first parameter is the file's name that we intend to read. The second parameter specifies the maximum number of bytes we wish to read from the file. 

 

We will be reading the file's contents named"demo.txt" using the fread() function in the example given below. It reads the entire contents of the file.

 

Program

<?php
$file = fopen("demo.txt", "r") or die("File not opened");
echo fread($file,filesize("demo.txt"));
fclose($file);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output

Reading A Single Line

We could read a single line from a file with PHP file handling methods. We can achieve this with the help of the fgets() function. This function requires the variable holding the filename to read a line from the file. After reading a line, the file pointer will move to the following line.

 

Program

<?php
$file = fopen("demo.txt", "r") or die("File not opened");
echo fgets($file);
fclose($file);
?>
You can also try this code with Online PHP Compiler
Run Code

 

 

Output

Reading A Single Character

To read a single character from a file with PHP file handling methods, we use the fgetc() function. After the fgetc() function is called, it reads a single character, and then the file pointer is moved to point to the next character.

 

Program

<?php
$file = fopen("demo.txt", "r") or die("File not opened");
while(!feof($file)) {
  echo fgetc($file) . "<br>";
}
fclose($file);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output

Checking End Of File

PHP file handling provides us with a way to check whether EOF (End Of File) has been reached. We use the feof() function for this. We commonly use the feof() function while looping data when we don’t know the length of the data. 

 

Program

<?php
$file = fopen("demo.txt", "r") or die("File not opened");
while(!feof($file)) {
  echo fgets($file) . "<br>";
}
fclose($file);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output

Writing To A File

Writing to files is one of the essential tasks in file handling. This is done in PHP file handling with the help of fwrite() function. We could write to a file using this function. It accepts two arguments as its parameters. The first parameter is the file’s name to which we want to write. The second parameter is the string to be written to the file.

 

Program

<?php
$file = fopen("file2.txt", "w") or die("File not opened");
$txt = "Snigdha Sathyanathan\n";
fwrite($file, $txt);
$txt = "Ranjul\n";
fwrite($file, $txt);
fclose($file);
?>
You can also try this code with Online PHP Compiler
Run Code

 

The contents of"file2.txt”:

PHP Overwriting

Overwriting is writing on top of some other data by replacing the pre-existing data. To overwrite any file, we need to open an existing file in the writing mode. When we open a file in writing mode, it will erase the entire data stored in the file, and any data we write onto that file will be written from the beginning of the file.

 

We know that the file we created in the previous section, i.e., "file2.txt”, contains some data. We will open our existing file"file2.txt" and write new data to it.

 

Program

<?php
$file = fopen("file2.txt", "w") or die("File not opened");
$txt = "Hello\n";
fwrite($file, $txt);
$txt = "New data is written to the file.\n";
fwrite($file, $txt);
fclose($file);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output 

Closing A File

Another function in PHP that makes PHP file handling effective is the fclose() function. Once a file is opened and processed as we desire, it is recommended to close the opened files. Closing all the files after use is considered a good programming practice. This function needs the file's name or the variable holding the file’s filename we wish to close.

 

Program

<?php
$file = fopen("demo.txt", "r");
fclose($file);
echo "File closed.";
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output

PHP file upload

Allowing a file to upload to the server has its dangers, we must ensure that the file will not have any malware present in it. The file upload configuration may not be enabled by default in your PHP. Let us see how to enable them and apply restrictions on the file.

 

To enable PHP file upload, go to the ‘php.ini’ file and look for a line that says ‘file_uploads’. Set it to on.

php.ini file

Adding Restrictions

Adding restrictions helps us limit the kind of file that the user will be able to upload to the server. It is good to think beforehand about the type of files that the website should accept and set restrictions accordingly. Some of the restrictions are checking if the file already exists, limiting the file size, limiting the file type, etc.

 

Let us see code snippets showing how to apply file upload restrictions.

 

Code:

// Check if file already exists
if (file_exists($file)) {
 echo "File already exists!";
 $Ok = 0;
}

// Allow certain file formats
if($imageFile != "jpg" && $imageFile != "png" && $imageFile != "jpeg") {
 echo "Only JPG, JPEG,and PNG files allowed.";
 $Ok = 0;
}

// Limit file upload size
if ($_FILES["file"]["size"] > 400000) {
 echo "Sorry, your file is larger than 4KB.";
 $Ok = 0;
}
You can also try this code with Online PHP Compiler
Run Code

Must Read PHP Projects With Source Code

FAQs

  1. What are the different modes in which we can open files in PHP?
    There are eight different modes in which we can open files in PHP. They are r, w, a, x, r+, w+, a+ and x+.
     
  2. How can we read only a single line from a file?
    We can read a single line from a file using the fgets() function.

Key Takeaways

File handling is the process of using and manipulating files in programs. We use PHP file handling functions to create, read, write, and close files in PHP. We can read a file using the PHP file handling function called readfile(), which reads a file and writes it to the output buffer. We could open a file using the fopen() function in one of the several modes provided by PHP. Opening a file in writing mode will erase all the previously stored data in the file. 

 

We could use the fread() and fwrite() function to read from and write to a file, respectively. The fgets() function reads a single line from the file, whereas the fgetc() function reads a single character from the file. We use the feof() function to check if we have reached the end of the file. The final PHP file handling function that we discussed was the fclose() function, which is used to close a file after our need for that file is over.

 

If you loved reading this article about PHP File Handling, check out Why Use PHP programming in 2021? Its Pros and Cons and 5 Best Free PHP Projects With Source Code To Work In 2021.

Live masterclass