Find the System Temp Directory with PHP
Sometimes it is useful to be able to save a file to the system’s temporary directory in a PHP application. Depending on the platform and it’s configuration however, this directory can be in a variety of places. As of PHP 5.2.1, there is a native function sys_get_temp_dir which will do the job. For earlier versions though, the following function will try to determine the temp directory for you and return its path as a string. If you use it and upgrade later, the code will degrade gracefully and switch to the native function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | if (!function_exists('sys_get_temp_dir')) { function sys_get_temp_dir() { // check environment variables. foreach (array('TMP', 'TEMP', 'TMPDIR') as $env_var) { if ($temp = getenv($env_var)) { return $temp; } } // test for a temp directory by having PHP create a temporary file. $temp = tempnam(__FILE__, ''); if (file_exists($temp)) { unlink($temp); return dirname($temp); } // couldn't find a temp directory. return null; } } |