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

kiks73 picture kiks73 · May 13, 2014 · Viewed 23.2k times · Source

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?

Answer

AeroX picture AeroX · May 13, 2014

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"));