2013年2月5日 星期二

tempnam修改

有時候在寫程式的時候會用到暫存檔 一般我們可能都是用PHP內建的tempnam來建立暫存檔 但有時候用到某些library時, 會去認檔案的副檔名,但內建的tempnam所產出的暫存檔副檔名皆為 .tmp 所以就自己另外寫了一個程式來替代暫存檔的產生

class File
{
    public static function tempnam($dir = NULL,$suffix = "tmp"){
        $name = strtoupper($suffix)."_".md5(time().mt_rand());
        if (empty($dir) == TRUE){
            $dir = sys_get_temp_dir();
        }
        $file = $dir.'/'.$name.".".$suffix;
        $handle = fopen($file, "w");
        fclose($handle);
        if (realpath($file) == TRUE)
        {
            register_shutdown_function(create_function("", 'if (realpath("'.$file.'") == TRUE){unlink("'.$file.'");}'));
            // register_shutdown_function(array("File", 'rmtempnam'),$file);
            return $file;
        }
        throw new Exception();
    }
} // End file

echo File::tempnam(NULL,"png");
// print xxxxxxx.png