如何在PHP中将文件内容复制到临时文件中?

15

我尝试了这个:

$temp = tmpfile();
file_put_contents($temp,file_get_contents("$path/$filename"));

但我遇到了这个错误:“警告:file_put_contents()期望参数1为字符串,”

如果我尝试:

echo file_get_contents("$path/$filename");
它将文件内容作为一个长字符串返回到屏幕上。 我错在哪里了?

2
tmpfile - 创建一个临时文件并返回一个文件指针,而不是字符串。 - AeroX
5
使用 tempnam 替代 tmpfile,它返回一个字符串文件名而不是资源。 - scragar
我在想参数列表是从零开始的。 - kiks73
2个回答

40

在您提供的示例中,您需要使用 tempnam() 而不是 tmpfile()

  • tempnam() 函数创建一个临时文件并将其路径作为字符串返回。然后,您可以将该字符串传递给 file_put_contents 函数。使用完毕后,必须手动删除临时文件。

  • tmpfile() 函数创建一个临时文件并返回用于 fwrite() 和其他文件操作函数的文件资源/指针。此外,在脚本执行结束时,tmpfile() 创建的临时文件会自动删除。


下面是使用 tempnam() 替代 tmpfile() 的示例代码:

$temp = tempnam(sys_get_temp_dir(), 'TMP_');

file_put_contents($temp, file_get_contents("$path/$filename"));

3
注意!在使用tempnam()函数时,如果你不再需要它,你需要手动删除文件,因为它不会自动删除。 - alkaponey
1
@alkaponey 没错,用简单的 unlink($temp); 就可以删除临时文件。 - tomloprod
2
copy("$path/$filename", $temp) 会使用更少的CPU和内存资源。 - Rvanlaak

24

tmpfile() 函数创建一个以读写(w+)模式打开的具有唯一名称的临时文件,并返回一个文件句柄,例如可用于fwrite。

$temp = tmpfile();
fwrite($temp, file_get_contents("$path/$filename"));

当文件被关闭时(例如通过调用fclose(),或者当没有任何对tmpfile()返回的文件句柄的引用时),该文件将自动删除,或者在脚本结束时。请参考php ref


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接