Temporary files
suggest changeTemporary files are commonly used in PHP for file uploads, report generation, processing intermediate image/video data, or interacting with external command-line tools. PHP provides built-in functions to safely create temporary files on disk, in-memory stream wrappers, and file cleanup mechanisms.
Locating the System Temporary Directory
Use sys_get_temp_dir() to retrieve the path of the directory PHP uses for temporary files (respecting OS environment variables like TMPDIR, TEMP, or TMP):
$tempDir = sys_get_temp_dir();
echo "System temp dir: " . $tempDir . PHP_EOL;
// Linux/macOS: /tmp
// Windows: C:\Users\<Username>\AppData\Local\Temp
tmpfile(): Automatically Cleaned Up on Close
The tmpfile() function creates a temporary file with a unique name in read/write binary mode (w+b). The file is automatically deleted when it is closed with fclose() or when the script ends:
// Create auto-deleting temp file handle
$handle = tmpfile();
if ($handle === false) {
throw new RuntimeException("Failed to create temporary file.");
}
// Write data
fwrite($handle, "Temporary report line 1\n");
fwrite($handle, "Temporary report line 2\n");
// Rewind to beginning to read back
rewind($handle);
while (($line = fgets($handle)) !== false) {
echo "Read: " . $line;
}
// Inspect stream metadata (e.g. underlying file path)
$meta = stream_get_meta_data($handle);
echo "Underlying path: " . $meta['uri'] . PHP_EOL;
// Closing the handle immediately deletes the file from disk
fclose($handle);
tempnam(): Creating Named Temporary Files on Disk
When you need an explicit file path—such as passing a path to an external CLI tool or third-party library—use tempnam():
$prefix = 'export_';
$tempPath = tempnam(sys_get_temp_dir(), $prefix);
if ($tempPath === false) {
throw new RuntimeException("Unable to generate temporary file name.");
}
try {
// Write contents to temporary file
file_put_contents($tempPath, "Data to be processed by CLI command");
// Perform operations with $tempPath
echo "Working with temp file: " . $tempPath . PHP_EOL;
} finally {
// Explicitly delete file when finished
if (file_exists($tempPath)) {
unlink($tempPath);
}
}
[!NOTE]
tempnam()creates the file on disk immediately with strict permissions (0600) to prevent race conditions (Time-of-Check to Time-of-Use / TOCTOU vulnerabilities). Always delete the file withunlink()when finished.
In-Memory Streams: php://memory and php://temp
If you don't strictly need a file path on disk, PHP's stream wrappers allow you to store temporary data efficiently in RAM:
php://memory: Keeps all data entirely in RAM. If data exceeds available memory, PHP will throw a memory limit error.php://temp: Keeps data in RAM until it reaches a configurable threshold (default: 2 MB), after which it transparently spills over to a temporary disk file.
// Spill over to disk once data exceeds 5 MB (5 * 1024 * 1024 bytes)
$stream = fopen('php://temp/maxmemory:5242880', 'r+');
// Write data (such as generating a CSV in memory)
fputcsv($stream, ['id', 'username', 'email'], escape: '');
fputcsv($stream, [1, 'alice', 'alice@example.com'], escape: '');
fputcsv($stream, [2, 'bob', 'bob@example.com'], escape: '');
// Rewind stream and output directly to HTTP response
rewind($stream);
fpassthru($stream);
fclose($stream); // Memory/temp file released
Managing Uploaded Temporary Files
Files uploaded through HTML forms or HTTP POST requests are saved by PHP in a temporary directory and stored in the $_FILES superglobal:
if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
$tempPath = $_FILES['avatar']['tmp_name'];
// Always use is_uploaded_file() and move_uploaded_file() for security
if (is_uploaded_file($tempPath)) {
$destination = __DIR__ . '/uploads/' . basename($_FILES['avatar']['name']);
move_uploaded_file($tempPath, $destination);
}
}
[!WARNING] Never use standard
copy()orrename()on$_FILES['...']['tmp_name']. Always useis_uploaded_file()andmove_uploaded_file()to ensure malicious users cannot manipulate the path.