How to Get System Temp Directory in PHP

This article explains how to dynamically locate your system’s temporary directory in PHP using the built-in sys_get_temp_dir() function. You will learn how the function works, see practical code examples for finding the directory, and understand how to safely create temporary files within it.

The most reliable way to find the temporary directory in PHP is by calling the sys_get_temp_dir() function. Introduced in PHP 5.2.1, this function returns the path of the directory PHP uses for temporary files by default on the hosting environment (such as /tmp on Linux or C:\Windows\Temp on Windows).

Basic Usage

To get the path of the temporary directory, simply call the function without any arguments:

<?php
$tempDirectory = sys_get_temp_dir();

echo "The system temporary directory is: " . $tempDirectory;
?>

How PHP Determines the Temporary Directory

The sys_get_temp_dir() function does not guess the path randomly. It determines the directory by checking specific environment variables in a strict order:

  1. The TMP environment variable.
  2. The TEMP environment variable.
  3. The TMPDIR environment variable.
  4. If none of these are set, it falls back to the system default (e.g., /tmp on Unix-like systems).

Creating a Temporary File

Once you have located the temporary directory, you can safely create temporary files inside it. It is recommended to use the tempnam() function to generate a unique file name in that directory to avoid overwriting existing files:

<?php
// Get the temporary directory
$tempDir = sys_get_temp_dir();

// Create a temporary file with a specific prefix
$tempFile = tempnam($tempDir, 'app_cache_');

if ($tempFile !== false) {
    // Write data to the temporary file
    file_put_contents($tempFile, "This is temporary data.");

    echo "Temporary file created at: " . $tempFile;

    // Perform your operations here...

    // Delete the file when done
    unlink($tempFile);
} else {
    echo "Failed to create a temporary file.";
}
?>

Cross-Platform Directory Separators

When appending file names manually to the temporary directory path, always ensure you use the correct directory separator. PHP provides the DIRECTORY_SEPARATOR constant, which automatically adapts to / on Linux/macOS and \ on Windows:

<?php
$tempDir = sys_get_temp_dir();
$filePath = $tempDir . DIRECTORY_SEPARATOR . 'my_custom_file.txt';
?>