Temporary Files And Directories in PHP

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

<?php

// Function to check for errors and throw an exception if one occurs
function check($result) {
    if ($result === false) {
        throw new Exception(error_get_last()['message']);
    }
}

// The easiest way to create a temporary file is by using the
// tempnam function. It creates a file and returns its path.
$tempFile = tempnam(sys_get_temp_dir(), 'sample');
check($tempFile);

// Display the name of the temporary file. On Unix-based OSes
// the directory will likely be /tmp. The file name starts with
// the prefix given as the second argument to tempnam and the
// rest is chosen automatically to ensure that concurrent calls
// will always create different file names.
echo "Temp file name: " . $tempFile . "\n";

// Clean up the file after we're done. The OS is likely to
// clean up temporary files by itself after some time, but
// it's good practice to do this explicitly.
register_shutdown_function(function() use ($tempFile) {
    unlink($tempFile);
});

// We can write some data to the file.
$data = pack('C*', 1, 2, 3, 4);
check(file_put_contents($tempFile, $data));

// If we intend to create many temporary files, we may prefer
// to create a temporary directory. In PHP, we can use the
// sys_get_temp_dir function along with mkdir to achieve this.
$tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'sampledir' . uniqid();
check(mkdir($tempDir));
echo "Temp dir name: " . $tempDir . "\n";

// Clean up the directory after we're done
register_shutdown_function(function() use ($tempDir) {
    rmdir($tempDir);
});

// Now we can synthesize temporary file names by prefixing
// them with our temporary directory.
$fileName = $tempDir . DIRECTORY_SEPARATOR . 'file1';
check(file_put_contents($fileName, pack('C*', 1, 2)));

To run the program, save it as temporary_files_and_directories.php and use the PHP CLI:

$ php temporary_files_and_directories.php
Temp file name: /tmp/sampleY8nLtm
Temp dir name: /tmp/sampledir5f9e8cb36e123

In this PHP version:

  1. We use tempnam() to create a temporary file, which is similar to os.CreateTemp() in the original example.
  2. sys_get_temp_dir() is used to get the system’s temporary directory.
  3. We use register_shutdown_function() to ensure cleanup of temporary files and directories, which is similar to using defer in the original code.
  4. mkdir() is used to create a temporary directory, and we generate a unique name using uniqid().
  5. file_put_contents() is used to write data to files, which is equivalent to os.WriteFile() in the original example.
  6. Error handling is done through a custom check() function that throws an exception on failure.

Note that PHP doesn’t have built-in functions for creating temporary directories like os.MkdirTemp() in Go, so we have to create our own implementation.