Basic PHP File Handling — Create, Open, Read, Write, Append, Close, and Delete
Written by David Walsh on December 20, 2007 · 13 Comments
I don't do a great deal of file handling in my PHP code -- most of my customers don't have a need for it or there's no room for file creation in the already tight budget. On the rare occasion that I do need to manipulate files, I keep the following tip sheet.
Create a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
Open a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //open file for writing ('w','r','a')...
Read a File
$my_file = 'file.txt'; $handle = fopen($my_file, 'r'); $data = fread($handle,filesize($my_file));
Write to a 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);
Append to a 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);
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);
Delete a File
$my_file = 'file.txt'; unlink($my_file);
your work is very good,but need your in creating my website about cricket
To avoid warnings, not forget if(!file_exists(‘myfile.txt’)) ;)
To avoid warnings, not forget if(!file_exists(‘myfile.txt’)) ;)
your work is very good,but need your in creating my website about cricket
Simple, but usefull!
Hello Everyone,
File handling functions in PHP are extremely useful and userfriendly.PHP includes a lot of built-in functions for handling files and directories. You can read, write, delete, and get lots of information on files through the use of these functions…………… for more details please check out the following link….
http://mindstick.com/Articles/07d7e4cf-b11c-49ea-8f4f-27c2e7f67c09/?File%20Handling%20in%20PHP
Thanks !!!!
Quite useful! Better to add the modes of the files. So that a person can understand more about php file handling… Thanks
This is basic stuff. How about a script for updating a record in an ASCII flat file?
so useful for freshers in php
Once again, I need a question answered and I find my way to David’s site. Thanks for all your help.
Gary
Nice and concise! Definitely bookmarking. +1
Just found something out thought I’d post here for everyone else,
To read a file line by line use fgets($file_handle)
$file_handle = fopen(“myfile”, “r”);
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $line;
}
fclose($file_handle);
so useful for freshers in php
[...] Source: http://davidwalsh.name/basic-php-file-handling-create-open-read-write-append-close-delete [...]