Jump to: navigation, search

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

Related Links


  1. PHP File Linux vs. Windows
  2. PHP File Information
  3. PHP File Create
  4. PHP File Close
  5. PHP File Read
  6. PHP File Read Reverse
  1. PHP File Write
  2. PHP File Write to end or append to
  3. PHP File Write at Beginning
  4. PHP File Write at specific location
  5. PHP File Truncate
  6. PHP File Replace a specific word
  1. PHP File Replace a specific word with associative array
  2. PHP File Copy File
  3. PHP File Copy Reverse
  4. PHP File Search within file
  5. PHP File Delete File
  6. PHP File Template
  1. PHP File Email Template
  2. PHP File Template with MySQL
  3. PHP File Access with MySQL
Navigation
Web
SQL
MISC
References