|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #10989 Wrong file writing
Submitted: 2001-05-21 10:57 UTC Modified: 2001-05-21 14:49 UTC
From: trax102 at hotmail dot com Assigned:
Status: Not a bug Package: Filesystem function related
PHP Version: 4.0 Latest CVS (2001-05-21) OS: Win2K-Win98-UNIX
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: trax102 at hotmail dot com
New email:
PHP Version: OS:


 [2001-05-21 10:57 UTC] trax102 at hotmail dot com
//At the end of the script "test.txt" should 
//contains "ADD1ADD2", but, as you can see,
//it will contains just "ADD2".
//Is there a work around for this problem ?

function read_file ($file_name)
	$file = fopen($file_name, "r");
	flock($file, 1); 
	$content = trim(fread($file, filesize($file_name)));
	flock($file, 3); 
	fclose ($file);
	return ($content);

function write_file ($content, $file_name)
	$file = fopen($file_name, "w");
	flock($file, 2);
	fwrite($file, $content);
	flock($file, 3);
	fclose ($file);

write_file("", $filename);

$content = read_file($filename);
$content .= "ADD1";
write_file($content, $filename);

$content = read_file($filename);
$content .= "ADD2";
write_file($content, $filename);


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2001-05-21 11:52 UTC] trax102 at hotmail dot com
Ok, I've found the solution: simply call clearstatcache() before filesize().
 [2001-05-21 11:55 UTC]
This should not be closed yet, as I think it's a valid bug.

 [2001-05-21 14:49 UTC]
It's not. The clearstatcache() is really needed (per manual). The result of filesize() is cached (and it's 0), so on all the calls to read_file() 0 bytes is read, hence 

write_file("", $filename);
# filesize() returns 0, and the result is cached

$content = read_file($filename);
# read filesize(), i. e. the cached 0 bytes. ok this time
$content .= "ADD1";
write_file($content, $filename);

$content = read_file($filename);
# read filesize(), i. e. the cached 0 bytes. this time it's not ok
# "" == $content
$content .= "ADD2";
write_file($content, $filename);

BTW I think it should be bogusified (user error).
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Wed Aug 17 04:05:45 2022 UTC