PHP File Write at Beginning
From w3cyberlearnings
Contents |
PHP Write to the beginning of a file
Write a new content to the beginning of a file.
File Content(test1.txt)
A peaceful person makes a peaceful heart. A peaceful heart A peaceful world A peaceful person A peaceful community
Example 1
<?php $file_name = 'test1.txt'; // open file for reading only $file_handler_1 = fopen($file_name, 'r') or exit('can not open file!'); // store the file content into $file_content_1 $file_content_1 = fread($file_handler_1, filesize($file_name)); // close file fclose($file_handler_1); ////////////////////////////////////// // open a file for writing $file_handler_2 = fopen($file_name, 'w+') or exit('can not open file!'); // file content $conent_string = "A peaceful school makes a paceful student"; // add a new content to the file content $content_content = $conent_string . "\n" . $file_content_1; // write back to a file if (fwrite($file_handler_2, $content_content)) { echo 'successfully append to the file<br/>'; } else { echo 'can not write to the file<br/>'; } fclose($file_handler_2); ?>
Output(test1.txt)
- Add A peaceful school makes a paceful student to the first line of the file.
A peaceful school makes a paceful student A peaceful person makes a peaceful heart. A peaceful heart A peaceful world A peaceful person A peaceful community