[wd_asp elements=’search’ ratio=’100%’ id=1]

Text file Read – Create – Save write/delete fopen

19th July 2013

Php - Strings

php codehaven
Read text file

Create a text file and add 122 to the file and save it


$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "122";
fwrite($myfile, $txt);
fclose($myfile);

Basic write to text file

$myname = "This will be added to text file";
$handle = fopen('mytextfile.php','a+');
fwrite ($handle,$myname);
fclose($handle);
echo "Text file written";

New file name

Creates a new file with the milliseconds time (Filenumber-1232233223.txt)
$date_to_add=substr(microtime(true) * 1000, 0, 13);
$handle = fopen('C:\Projects\dev\Filenumber-'.$date_to_add.'.txt','a');
fwrite ($handle,$writethis);
fclose($handle);

When run, this creates a text file (you may need permissions to write), the ‘a’ stands for append and will add a new line every time to the file.

Write to specific line

Delete Text file

$filetodelete = "testFile.txt";
unlink($filetodelete);

Delete all files in folder


$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}

Rename file

$old = '/tmp/today.txt';
$new = '/tmp/tomorrow.txt';
rename($old, $new) or die("Unable to rename $old to $new.");

Copy file

$old = '/tmp/yesterday.txt';
$new = '/tmp/today.txt';
copy($old, $new) or die("Unable to copy $old to $new.");

“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” (Write only. Opens and writes to the end of the file or creates a new file if it doesn’t exist)
“a+” (Read/Write. 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)