Skip to content

PHP File Handling

PHP File Handling is very impotent for serious programmers, we often use File Handing methods in web development, In this post i will cover file – Create, Open, Read, Write, Append, Close, and Delete Methods.

Create a File

$file = 'file.txt';
$handle = fopen($file, 'w') or die('Cannot open file:  '.$file); 

Open a File

$file = 'file.txt';
$handle = fopen($file, 'w') or die('Cannot open file:  '.$file);

Read a File

$file = 'file.txt';
$handle = fopen($file, 'r');
$data = fread($handle,filesize($file));

Write to a File

$file = 'file.txt';
$handle = fopen($file, 'w') or die('Cannot open file:  '.$file);
$data = 'This is the data';
fwrite($handle, $data);

Append to a File

$file = 'file.txt';
$handle = fopen($file, 'a') or die('Cannot open file:  '.$file);
$data = 'New data line 1';
fwrite($handle, $data);
$new_data = "n".'New data line 2';
fwrite($handle, $new_data);

Delete a File

$file = 'file.txt';
unlink($file);

Close a File

$file = 'file.txt';
$handle = fopen($file, 'w') or die('Cannot open file:  '.$file);
fclose($handle);

File Handling Modes list

Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments