Create and Clean Up Temporary Files in PHP

Last updated: August 28, 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.

Reference: PHP tempnam reference.

admin

admin