Basic File Operations Create,Write,Read,Append and Delete In PHP

Thought we don't use file operation regularly in programming, we should learn some basic file operation. In some cases these file may simplify our complex problem. In this lesson we will learn basic file operation in our PHP.
Basic File Operations Create,Write,Read,Append and Delete Operations In PHP Creating File

<?php  
$file = 'file.txt'; 
//To Create File 
$fp = fopen($file, 'w') or die('Cannot open file: '.$file); 
if($fp){  
echo "file created successfully";  
} 
fclose($fp);  
?> 

Write To File

<?php  
//To Write to the file 
$file = 'file.txt'; 
$fp = fopen($file, 'w') or die('Cannot open file: '.$file); 
$data = 'Line1:This is Line1 data'; 
fwrite($fp, $data);  
fclose($fp);  
?> 

Read File

<?php  
//To Read File 
$file = 'file.txt'; 
$fp = fopen($file, 'r'); 
$data = fread($fp,filesize($file)); 
echo $data;  
?> 

Append To File

<?php  
//append to the file 
$file = 'file.txt'; 
//opening a file in append mode. 
$fp = fopen($file, 'a') or die('Cannot open file: '.$file); 
$data = 'Line no.1: Data on first line'."n"; 
fwrite($fp, $data);  
fclose($fp);  
?> 

Deleting File

<?php  
//deleteing file from hard desk 
$file = 'file.txt'; 
unlink($file);  
?> 

Get posts by email

Like what you're reading? Get these posts delivered to your inbox.