Create and Clean Up Temporary Files in PHP

Last updated: August 29, 2026.

Temporary files support exports, image processing, and API payloads. Give them an application-specific prefix and delete them in a finally block even when processing fails.

Use a temporary file safely

<?php
$path = tempnam(sys_get_temp_dir(), 'wcs_export_');
if ($path === false) throw new RuntimeException('Cannot create temporary file.');
try {
    if (file_put_contents($path, "id,name\n1,Ada\n") === false) throw new RuntimeException('Write failed.');
    // Process or send the file.
} finally {
    if (is_file($path)) unlink($path);
}

Clean only owned files

  • Use an application-specific filename prefix.
  • Delete files in a finally block.
  • For scheduled cleanup, require both prefix and age.
  • Never recursively clear the system temporary directory.

Give each job ownership of its files

Use a dedicated directory or recognizable prefix so cleanup code can distinguish application files from unrelated system data. A finally block handles normal failures, while scheduled cleanup handles abandoned jobs.

Test a failed write, a process terminated before cleanup, and two concurrent jobs. Scheduled cleanup should ignore recent files and should never recursively clear the shared system temporary directory.

  • Use restrictive permissions.
  • Generate unpredictable names.
  • Apply an age threshold during scheduled cleanup.

Keep resource limits explicit and make failure cleanup part of the example. Log enough context to diagnose the operation without recording passwords, private message bodies, or uploaded file contents.

Continue with ZIP archives, email attachments, and large CSV processing.

Practical implementation check

Put the operation in a small function or service with explicit inputs and a clear failure result. Test invalid input, missing extensions, permission failures, and concurrent requests. Production logs should identify the operation and record ID without storing secrets or private content. Clean up partially created files or queue records when any later step fails.

Return a clear result to the caller and keep user-facing messages separate from detailed diagnostics. This makes the same code usable from a web request, command-line job, or queue worker.

Reference: PHP tempnam reference.

admin

admin