簡體   English   中英

使用 php 創建具有特定擴展名的臨時文件

[英]Create a temp file with a specific extension using php

如何在 php 中創建具有指定擴展名的臨時文件。我遇到了tempnam()但使用它無法指定擴展名。

我發現的最簡單的方法是創建臨時文件,然后重命名它。 例如:

 $tmpfname = tempnam(sys_get_temp_dir(), "Pre_");
 rename($tmpfname, $tmpfname .= '.pdf');

我的方法是使用tempnam

$file = tempnam(sys_get_temp_dir(), 'prefix');
file_put_contents($file.'.extension', $data);
{
   //use your file
}
unlink($file);//to delete an empty file that tempnam creates
unlink($file.'.extension');//to delete your file

這可能會模擬mkstemp() (參見http://linux.die.net/man/3/mkstemp ),實現您想要做的:

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;
}

所以你可以這樣做:

if( ($f = mkstemp("test-XXXXXX.txt")) ) {
  fwrite($f, "test\n");
  fclose($f);
}
public static function makeTempFileInFolder($prefix, $suffix, $folder="")
{
  if (strlen($folder)==0) $folder = sys_get_temp_dir();
  do { 
    $file = $folder."/".$prefix.rand(1,99999).time().$suffix; 
  } while (file_exists($file));
  return $file;
}

假設 tempnam() 給你一個“文件名”的文件。 您將其移動到“filename.ext”。 在任何時候,tempnam() 都可以再次為您提供“文件名”。 如果您檢查“filename.ext”,拒絕 tempnam() 給出的文件名,並再次調用它,您仍然有可能在一步與另一步之間創建一個具有相同名稱的文件。 (這在 tempnam() 文檔頁面的用戶評論中進行了討論: https://www.php.net/manual/en/function.tempnam.php。

但是,如果您只保留由 tempnam() 創建的文件(在刪除“filename.ext”之前不刪除“filename”)並使用該文件名 + 擴展名,那么 tempnam() 就沒有機會使用它文件名再次(據我所知)。 是的,每個文件都有“文件名”和“文件名.ext”是很麻煩的。 另一方面,它解決了問題。

除了附加參數外,與tempnam()相同:

function tempnamp($dir, $prefix, $postfix) {
  $maxAttempts = 1000;
  // Trim trailing slashes from $dir.
  $dir = rtrim($dir, DIRECTORY_SEPARATOR);
  // If we don't have permission to create a directory, fail, otherwise we will
  // be stuck in an endless loop.
  if (!is_dir($dir) || !is_writable($dir)) return false;
  // Make sure characters in prefix and postfix are safe.
  if (strpbrk($prefix, '\\/:*?"<>|') !== false) return false;
  if (strpbrk($postfix, '\\/:*?"<>|') !== false) return false;
  // Attempt to create a random file until it works.
  $attempts = 0;
  do
  {
    $path = $dir.DIRECTORY_SEPARATOR.$prefix.mt_rand(100000, mt_getrandmax()).$postfix;
    $fp = @fopen($path, 'x+');
  } while (!$fp && $attempts++ < $maxAttempts);
  if ($fp) fclose($fp);
  return $path;
}

名稱末尾的“p”代表“后綴”。

重命名它,用 pathinfo 找到擴展名,然后用你想要的擴展名替換。

$tmpfname = tempnam(sys_get_temp_dir(), 'FOO');
$newname = str_replace(pathinfo($tmpfname, PATHINFO_EXTENSION),'pdf',$tmpfname);
rename($tmpfname, $newname);
//do what you want with $newname
unlink($newname);

我更喜歡這個解決方案:

$uid = uniqid('', true);
$path = sys_get_temp_dir() . "some_prefix_$uid.myextension";

注意:我沒有將前綴放在uniqid中,因為恕我直言,這不是它的職責

也許使用

move_uploaded_file($tmp_name, "$uploads_dir/$name.myextension");

http://php.net/manual/en/function.move-uploaded-file.php#example-2209

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM