How can I copy a file content into a temporary file in PHP? [duplicate]

一个人想着一个人 提交于 2019-12-04 19:06:10

问题


I tried this:

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

But I get this error: "Warning: file_put_contents() expects parameter 1 to be string,"

If I try:

echo file_get_contents("$path/$filename");

It return to screen the file content as a long string. Where am I wrong?


回答1:


tmpfile() creates a temporary file with a unique name in read-write (w+) mode and returns a file handle to use with fwrite for example.

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

The file is automatically removed when closed (for example, by calling fclose(), or when there are no remaining references to the file handle returned by tmpfile()), or when the script ends. look at php ref.




回答2:


In the example you give you want tempnam() and not tmpfile().

  • tempnam() creates a temporary file and returns the path to it as a String. You can then pass that string into file_put_contents. You must remember to manually delete the temporary file once you are done with it.

  • tmpfile() creates a temporary file and returns a file resource/pointer to use with fwrite() and other file manipulation functions. In addition, once the script execution ends, the temporary file created by tmpfile() is automatically deleted.


Here is your example script using tempnam() instead of tmpfile():

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

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


来源:https://stackoverflow.com/questions/23633728/how-can-i-copy-a-file-content-into-a-temporary-file-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!