PHP - File Handling

In this topic we discuss on php file handling that include the Create, Open, Read, Write, Append, Close, and Delete file using php file handling concept the following example of all type of file operation in php.

Create a File


<?php
	$my_file = 'file.txt';
	$ha_file = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
?>
							
							

Open a File


<?php
	$my_file = 'file.txt';
	$ha_file = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
?>
							
							

Read a File


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

Write a File


<?php
	$my_file = 'file.txt';
	$ha_file = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
	$data = 'This is the data';
	fwrite($ha_file, $data);
?>
							

Append a File


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

Close a File


<?php
	$my_file = 'file.txt';
	$ha_file = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
	//write data here
	fclose($ha_file);
?>
							
							

Delete a File


<?php
	$my_file = 'file.txt';
	unlink($my_file);
?>
							
							
Share Share on Facebook Share on Twitter Share on Google+ Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit