Search code examples
phptemporary-files

Create a temp file with a specific extension using php


How do I create a temporary file with a specified extension in php. I came across tempnam() but using it the extension can't be specified.


Solution

  • This might simulate mkstemp() (see http://linux.die.net/man/3/mkstemp) a bit, achieving what you want to do:

    function mkstemp( $template ) {
      $attempts = 238328; // 62 x 62 x 62
      $letters  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $length   = strlen($letters) - 1;
    
      if( mb_strlen($template) < 6 || !strstr($template, 'XXXXXX') )
        return FALSE;
    
      for( $count = 0; $count < $attempts; ++$count) {
        $random = "";
    
        for($p = 0; $p < 6; $p++) {
          $random .= $letters[mt_rand(0, $length)];
        }
    
        $randomFile = str_replace("XXXXXX", $random, $template);
    
        if( !($fd = @fopen($randomFile, "x+")) )
          continue;
    
        return $fd;
      }
    
      return FALSE;
    }
    

    So you could do:

    if( ($f = mkstemp("test-XXXXXX.txt")) ) {
      fwrite($f, "test\n");
      fclose($f);
    }