Why Your Empty File Happens and How to Fix It
The code snippet you provided creates a file, but it remains empty because of how fopen() behaves when used with the "a" (append) mode on an existing or newly created file: it opens the file for writing, but nothing is actually written before the file handle is closed. In your script, you call fopen(), then immediately call fclose(). There is no fwrite() call between them, so the file contains zero bytes. This isn't a bug in PHP; it's just missing the write step.
To add text like "Cats chase mice", you need to open the file, write data to it, and then close the handle. Here's the minimal change:
<?php
$file = fopen("lidn.txt", "a"); // or "w" if you want to overwrite existing contents
if ($file === false) {
die('Unable to open file for writing');
}
$line = "Cats chase mice\n";
fwrite($file, $line);
fclose($file);
?>
Key points:
fopen()returns a resource on success andfalseon failure. Always check the return value before using the handle."a"opens for appending at the end of the file. If the file doesn't exist, it is created. Use"w"if you want to truncate (erase) existing contents first.fwrite()writes a string to the stream. The newline character\nensures each line terminates properly on most systems.fclose()releases the resource and flushes buffered data to disk.
A common mistake is assuming that opening and closing the file automatically writes something. It doesn't. You must call a write function, such as fwrite(), or use file_put_contents() for simpler cases.
When to Use file_put_contents Instead
For many tasks, file_put_contents() is more convenient:
<?php
$content = "Cats chase mice\n";
$file = 'lidn.txt';
// Append without truncating
if (file_put_contents($file, $content, FILE_APPEND | LOCK_EX) === false) {
// handle error
}
?>
FILE_APPENDprevents truncation if the file exists.LOCK_EXadds an exclusive lock on supported platforms, reducing race conditions when multiple processes might write to the same file.
This is preferable when you want atomic appends and don't need low-level stream control. It also handles buffering internally in most cases, so explicit fclose() isn't required unless you're managing persistent streams or large streams where manual flushing matters.
Error Handling and Permissions
If your script fails to write, check:
- File permissions: the web server user must be able to write to the directory and file. On Linux, ensure the parent directory is writable (e.g.,
chmod 755on dirs,644or664on files depending on ownership). - Disk space: insufficient space causes failures that might not surface immediately until a write happens.
- Open file limits: too many simultaneous streams can hit system limits (
ulimit -n).
Use try/finally with explicit checks in larger applications to ensure handles are released even if an error occurs:
<?php
$file = 'lidn.txt';
$handle = @fopen($file, 'a'); // suppress notice for cleaner error handling logic
if ($handle === false) {
throw new RuntimeException('Failed to open file');
}
try {
fwrite($handle, "Cats chase mice\n");
} finally {
fclose($handle);
}
?>
Security Considerations
Avoid embedding user input directly into filenames or content without validation. Path traversal attacks can occur if you accept arbitrary paths like ../../etc/passwd. Validate and sanitize all inputs before constructing file names. For dynamic content, store it in designated directories with restricted permissions.
If you're building a larger application where file writing is part of a workflowâlogging events, exporting data, or persisting configurationâconsider using a framework's built-in facilities. Laravel provides robust helpers for writing to disk and managing storage drivers that abstract away these details. For more information on structured file handling and storage options within the Laravel ecosystem, see https://laravelcompany.com.
Summary of Best Practices
- Always check the return value of
fopen()andfile_put_contents(). - Use
fwrite()with"a"orfile_put_contents()withFILE_APPENDfor appending. - Include
\nin strings to ensure proper line termination. - Handle errors explicitly; don't rely on silent failures.
- Respect permissions, disk limits, and security when constructing paths or content.
With these practices, your file will contain exactly what you expect, and your scripts will behave predictably across environments.