Read text file
1 2 3 4 5 6 7 |
<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("webdictionary.txt")); fclose($myfile); ?> |
Create a text file and add 122 to the file and save it
1 2 3 4 5 6 |
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = "122"; fwrite($myfile, $txt); fclose($myfile); |
Basic write to text file
1 2 3 4 5 6 7 |
$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)
1 2 3 4 5 6 |
$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.
1 2 3 4 5 6 7 8 9 10 |
<?php $myname = "drax"; $date_to_add_to_txt=date("d-m-Y H:i:s"); $handle = fopen('mynewfile.txt','a'); fwrite ($handle,$date_to_add_to_txt." - ".$myname."rn"); fclose($handle); echo "Text file written"; ?> |
Write to specific line
1 2 3 4 5 6 7 8 9 10 11 |
<?php $file = 'test1.txt'; $line_looking = 4; $lines = file($file, FILE_IGNORE_NEW_LINES); $lines[$line_looking] = 'Codehavens great!'; file_put_contents($file, implode("\n", $lines)); ?> |
Delete Text file
1 2 3 4 |
$filetodelete = "testFile.txt"; unlink($filetodelete); |
Delete all files in folder
1 2 3 4 5 6 7 |
$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
1 2 3 4 5 |
$old = '/tmp/today.txt'; $new = '/tmp/tomorrow.txt'; rename($old, $new) or die("Unable to rename $old to $new."); |
Copy file
1 2 3 4 5 |
$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)