How to copy file contents to temporary file in PHP?

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 a string,"

If I try:

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

It returns to display the contents of the file as a long string. Where am I mistaken?

+4
source share
2 answers

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

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

The file is automatically deleted when closing (for example, by calling fclose () or when there are no remaining links to the file descriptor returned by tmpfile ()), or when the script ends. look php ref .

+9

tempnam(), tmpfile().


script tempnam() tmpfile():

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

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

Source: https://habr.com/ru/post/1540380/


All Articles