PHP File Write function

Write data safely to a file

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);
?>
File create or Write 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.

If the file does not exist then one new file will be created. Use normal server filesystem permissions rather than making generated files world-writable. However, we can check the presence of a file by using file_exists function.
Read the content of a file by using fopen()
We can use fwrite() to write counter and many other scripts if you are not using any database for storing data. . Here we will see how to write to a file.

Reading, changing and writing a controlled file

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');
}

Page Hit counter Script

Create one page hit counter where a incremental number is stored in a text file each time the file is opened..

File Directory Functions File Delete
PHP


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer