Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using copy() with destination created by tempnam()

Tags:

php

While debugging a problem in a framework, I came across some strange behavior when using tempnam() to create a destination for a copied file.

Here is a reduced test case:

touch ('/tmp/file.txt');
file_put_contents('/tmp/file.txt', 'test');
$dst = tempnam('/tmp', 'dst');
copy('/tmp/file.txt', $dst);
var_dump(filesize($dst));

Obviously, I would expect the var_dump() at the end to output "4", since this is the size of the the source file, but instead, it always comes back as zero, meaning that the destination file is empty, although copy() returns true. I tested on PHP 5.4.4 and 5.3.10, with identical results.

I know that I can change my code to use fwrite() or some similar construct, but what I would really like to know is, why doesn't it work the way I wrote it?

Update

It seems that this is in fact a PHP bug, calling clearstatcache() before filesize() produces the correct result, so in fact the copy was successful either way, it's filesize() that is lying. See https://bugs.php.net/bug.php?id=65701 and https://github.com/php/php-src/pull/459

like image 428
user2792352 Avatar asked Nov 12 '22 21:11

user2792352


1 Answers

It seems that this is in fact a PHP bug, calling clearstatcache() before filesize() produces the correct result, so in fact the copy was successful either way, it's filesize() that is lying. See https://bugs.php.net/bug.php?id=65701 and https://github.com/php/php-src/pull/459

like image 157
user2792352 Avatar answered Nov 15 '22 01:11

user2792352