PHP Tutorial Tutorials - PHP File Write

PHP File Write

PHP provides various functions to write data into file:

  • fwrite()
  • file_put_contents()

Writing the Files Using PHP fwrite() Function

The PHP fwrite() function is used to write the contents of string to the file.
You need to open the file in r+, w, w+, x, x+, c or c+mode.

Syntax

fwrite(file handle, string)

Example

<?php
$filename = "data.txt";
$fp = fopen($filename, 'w'); // opens file in write-only mode
fwrite($fp, "data 1\n"); // \n is escape string represents new line
fwrite($fp, "data 23");
fclose($fp);
?> 

data.txt

data 1
data 23

Writing the Files Using PHP file_put_contents() Function

An alternative way to write data into file is using the file_put_contents() function.

Syntax

file_put_contents($filename, $data,[$flags])

$flags - FILE_APPEND: append the content to the end of the file
$flags - LOCK_EX: prevent anyone else writing to the file at the same time

<?php
$filename = "data.txt";
$data = " data string ";
file_put_contents($filename, $data);
$data = " append content ";
file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
?>

data.txt

 data string  append content 
Date:2019-10-01 03:03:16 From:www.Lautturi.com author:Lautturi