Using PHP tmpfile() to Create and Manage Temporary Files
This article explains how the PHP tmpfile() function creates a unique temporary file that is automatically removed when the script ends, demonstrates its syntax and usage with example code, and highlights important considerations such as resource handling and manual deletion with unlink().
In PHP programming, handling files is a common operation, and when a temporary file is needed without persisting it, the tmpfile() function provides a convenient solution.
The tmpfile() function is part of PHP's file system functions; it creates a temporary file with a unique name that is automatically deleted when the file handle is closed or the script terminates, thus not occupying permanent disk space.
Syntax:
resource tmpfile ( void )The function takes no parameters and returns a file handle (resource) that can be used for reading and writing.
Below is a simple example that demonstrates creating a temporary file with tmpfile() and writing data to it:
<?php
$file = tmpfile(); // 创建一个临时文件
if ($file) {
fwrite($file, 'Hello, World!'); // 将数据写入临时文件
fseek($file, 0); // 将文件指针定位到文件开头
echo fread($file, filesize($file)); // 从文件中读取并输出数据
fclose($file); // 关闭并删除临时文件
}
?>In the example, tmpfile() creates a temporary file and returns a handle stored in $file . The script writes a string to the file with fwrite() , rewinds the pointer using fseek() , reads and outputs the content with fread() , and finally closes the handle with fclose() , which also deletes the temporary file.
Note that the handle returned by tmpfile() is a resource type, which can be used with other file functions such as fwrite() , fseek() , and fclose() .
Additionally, the temporary file created by tmpfile() is automatically removed at script termination; if manual deletion is desired at any point, the unlink() function can be used.
In summary, tmpfile() is a very convenient PHP file system function for creating temporary files without needing to specify a filename or path, useful for short‑lived operations, but the files exist only during script execution and are not persisted on disk.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.