Use file_put_contents() for straightforward writes and fopen()/fwrite() when you need finer control. LOCK_EX can reduce collisions when multiple requests may write to the same file.
$file = __DIR__ . '/notes.txt';
$data = "New entry\n";
$result = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
if ($result === false) {
echo 'Unable to write the file.';
}The examples below show additional variations and practical file-handling cases.
<?php
$body_content = "This is my content\n";
$file_name = __DIR__ . '/test_file.txt';
$fp = fopen($file_name, 'wb');
if ($fp === false) { exit('Unable to open file'); }
fwrite($fp, $body_content);
fclose($fp);
?>
We can write to a file by using fwrite() function PHP. Please note that we have to open the file in write mode and if write permission is there then only we can open it in write mode. Do not accept an unrestricted filename or path from the URL. Resolve the target from a server-controlled location, read it, modify the content, then write it back while checking each operation.
$filename = __DIR__ . '/data/test.html';
$contents = file_get_contents($filename);
if ($contents === false) { exit('Unable to read file'); }
$search = ['<h3>', '</h3>'];
$replace = ['<pre><code>', '</code></pre>'];
$contents = str_replace($search, $replace, $contents);
if (file_put_contents($filename, $contents, LOCK_EX) === false) {
exit('Unable to write file');
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.