The get_temp_dir() WordPress PHP function determines a writable directory for temporary files.
Usage
$temp_dir = get_temp_dir(); echo 'Temporary Directory: ' . $temp_dir;
Output: Temporary Directory: /path/to/temp/dir/
Parameters
- None
More information
See WordPress Developer Resources: get_temp_dir()
Examples
Create a temporary file in the temp directory
This example creates a temporary file in the writable temp directory.
$temp_dir = get_temp_dir(); $temp_file = tempnam($temp_dir, 'my_prefix_'); // Create a file with a unique name and 'my_prefix_' prefix in the temp directory
Save uploaded file to temp directory
This example saves an uploaded file to the writable temp directory.
$temp_dir = get_temp_dir(); $uploaded_file = $_FILES['uploaded_file']['tmp_name']; $destination = $temp_dir . '/uploaded_file.txt'; move_uploaded_file($uploaded_file, $destination); // Move the uploaded file to the temp directory
Create a temp directory for image processing
This example creates a temporary directory for storing processed images.
$temp_dir = get_temp_dir();
$images_temp_dir = $temp_dir . '/image_processing';
if (!file_exists($images_temp_dir)) {
mkdir($images_temp_dir, 0777, true);
}
// Create a new directory 'image_processing' inside the temp directory
Cache data in a temp file
This example caches data in a temporary file in the writable temp directory.
$temp_dir = get_temp_dir(); $data = 'Sample data to be cached'; $cache_file = $temp_dir . '/cache.txt'; file_put_contents($cache_file, $data); // Save the data to a cache file in the temp directory
Clear temp files older than a day
This example deletes temporary files older than a day from the temp directory.
$temp_dir = get_temp_dir();
$files = glob($temp_dir . '/*');
$now = time();
foreach ($files as $file) {
if (is_file($file) && $now - filemtime($file) >= 86400) {
unlink($file);
}
}
// Delete files older than a day from the temp directory