我尝试了这个:
$temp = tmpfile();
file_put_contents($temp,file_get_contents("$path/$filename"));
但我遇到了这个错误:“警告:file_put_contents()期望参数1为字符串,”
如果我尝试:
echo file_get_contents("$path/$filename");
它将文件内容作为一个长字符串返回到屏幕上。
我错在哪里了?我尝试了这个:
$temp = tmpfile();
file_put_contents($temp,file_get_contents("$path/$filename"));
但我遇到了这个错误:“警告:file_put_contents()期望参数1为字符串,”
如果我尝试:
echo file_get_contents("$path/$filename");
它将文件内容作为一个长字符串返回到屏幕上。
我错在哪里了?在您提供的示例中,您需要使用 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"));
unlink($temp);
就可以删除临时文件。 - tomloprodcopy("$path/$filename", $temp)
会使用更少的CPU和内存资源。 - Rvanlaaktmpfile()
函数创建一个以读写(w+)模式打开的具有唯一名称的临时文件,并返回一个文件句柄,例如可用于fwrite。
$temp = tmpfile();
fwrite($temp, file_get_contents("$path/$filename"));
当文件被关闭时(例如通过调用fclose(),或者当没有任何对tmpfile()返回的文件句柄的引用时),该文件将自动删除,或者在脚本结束时。请参考php ref。
tempnam
替代tmpfile
,它返回一个字符串文件名而不是资源。 - scragar