File handling in PHP with Source code

File handling in PHP with Source code

Introduction

File handling is the main part of any application or website. This handling part can perform various task. Such as open file, read, write and delete files.

File handling is very userful. As a programming language PHP can perform the similar task like other program. Well PHP is a scripting programming language. We can perform various task using this program. The php program is especially built for web development. But we can still do various works using php. It is simple and easy to learn. In this tutorial we are going to open a txt file, read, write and delete the file. It is easy to open a txt file using computer.

We are doing this file handling function using php program. You will be provided the source code along with this article. We will be using php built in functions. Such as fopen, fread, fwrite, unlink etc. Make sure that all the php files has opening and closing tag. You will get error if not use tag properly.


The fopen() function is useful for creating a new txt file. You must provide a file name. A example.txt file will be created. I am proving example.txt for my file name. see the code for creating file below.

<?php 
$file = "example.txt";
$handle = fopen($file, 'w');
fclose($handle);
?>

 The fwrite() function writes on the newly created file. You can write anything on that file using fwrite() function. Write “I like php” and see what happens. The example.txt file that is created is use for writing. We are writing on same file.

<?php
$file = "example.txt";
if($handle = fopen($file, 'w')){
    fwrite($handle, 'I like PHP');
    fclose($handle);
} else {
    echo "The app was not able to write on file";
}
?>

further file handling

For reading from file we use fread() php function. We are reading from the example.txt file. The text that we are writing will show using this function. See the code for reading below.

<?php
$file = "example.txt";
if($handle = fopen($file, 'r')){
echo $content = fread($handle, filesize($file));
    fclose($handle);
} else {
    echo "The app was not able to write on file";
}
?>

Unlink function is useful for deleting php files. To delete the example.txt unlink function is used. If you are on same folder you can write unlink and give the file name. See the code for deletion below.

<?php
unlink("example.txt");
?>

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •