PHP File Handling - Create, Edit, Delete, Open, Close, Append
icon-search
PHP File Handling - Create, Edit, Delete, Open, Close, Append

PHP File Handling - Create, Edit, Delete, Open, Close, Append

PHP File Handling - Create, Edit, Delete, Open, Close, Append

PHP file handling in php is a simple technique by which you can use to create, edit, delete, append, prepend, open, close and write to a text file the file format can be any.

So to understand PHP file handling I have created small snippets of PHP code:

PHP file handling - create a file :

This is a simple PHP code snippet that will help you to create a file your file can be any but in my case I am using text file.


<?php
//create file
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file
?>


PHP file handling - open a file :

This PHP script will allow you to open up a file in my case I am going to open file.txt file which we have created above


<?php
//open file
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //open file for writing ('w','r','a')...
?>


PHP file handling - read a file :

This PHP snippet will make a sense to read a file.


<?php
//read file
$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
?>

PHP file handling - write to a file :


Here is a simple PHP snippet that will allow you to to write to a file

<?php
//write to file
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
$data = 'This is the data';
Fwrite($handle, $data);
?>

PHP fil handling - append to a file :

What is PHP snippet will allows us to append a text or a string into a file

<?php
//append to file
$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file:  '.$my_file);
$data = 'New data line 1';
Fwrite($handle, $data);
$new_data = "\n".'New data line 2';
Fwrite($handle, $new_data);
?>


PHP file handling - close the file :

It's common that when we are doing some file handling function in PHP in the first line we have to open that text file and in the last line we have to close that file. So this snippet will make a sense to close a file.


<?php
//close a file
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
//write some data here
Fclose($handle);
?>

PHP file handling - delete a file :

This is last but not the least, by using this function basically called unlink() in PHP, you can delete any file by providing the name show our this snippet will do that work for us.

<?php
//delete a file
$my_file = 'file.txt';
Unlink($my_file);
?>

Conclusion of PHP File Handling:

This was a simple tutorial about PHP file handling I think you might understand all the things and if you have any difficulty you can simply ask me that in the comment section below I will be glad to answer it.

Disqus Codes

No comments

Notifications

Disqus Logo