Question

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?

Était-ce utile?

La solution 2

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.

Autres conseils

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"));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top