在 move_uploaded_file() 之后对移动文件调用 PHP unlink() 失败

Calling PHP unlink() after move_uploaded_file() on moved file fails

我正在将上传到我的服务器的文件发送到 Amazon S3。为此,我:

Windows 服务器 运行 PHP/Apache.

我可以稍后在脚本完成后取消链接 运行。在脚本外部调用 unlink() 命令会立即从服务器中删除该文件。我试图弄清楚如何从 move_uploaded_file() 中释放文件,但搜索了一段时间后找不到任何东西。

我确实使用 $thumb1 = new Imagick($filetothumbnail); 并创建了缩略图。但我随后打电话给

$thumb1->clear();
$thumb1->destroy();

也许 Imagick 仍然打开着文件?然而,我已经用一个没有制作缩略图的 excel 文件对此进行了测试,并且该文件仍然无法从服务器中删除。

if(isset($_FILES['file'])){
  $name = $_FILES['file']['name'];
  $size = $_FILES['file']['size'];
  $tmp = $_FILES['file']['tmp_name'];
  $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

  $newname = time().'_'.$j['id'].'_'.$name;
  $thumbname = 'tn_'.time().'_'.$j['id'].'_'.$name;
  move_uploaded_file($_FILES["file"]["tmp_name"], "temp-uploads/".$newname);

  //Now, generate thumbnail for the file:
  $filetothumbnail = $_SERVER['DOCUMENT_ROOT'].'/temp-uploads/'.$newname;
  $thumbnails = $_SERVER['DOCUMENT_ROOT'].'/temp-uploads/thumbs/';

  //Send to AWS Bucket
  $s3_filepath = 'project-assets/'.$newname;
  upload_s3_file($s3_filepath, "temp-uploads/".$newname);

  $filepath = s3url.$s3_filepath;

  if($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif'){

  $thumb1 = new Imagick($filetothumbnail);
  $compression_type = Imagick::COMPRESSION_JPEG; 

  $thumb1->setImageCompression($compression_type); 
  $thumb1->setImageCompressionQuality(40);
  $thumb1->thumbnailImage(500, 0);
  $thumb1->setImageFormat('jpg');
  $thumb1->writeimage($thumbnails.$thumbname);
  $thumb1->clear();
  $thumb1->destroy();

  //If thumbnail is there. Only for certain file types.
  $s3_thumbpath = 'project-thumbnails/'.$thumbname;
  upload_s3_file($s3_thumbpath, "temp-uploads/thumbs/".$thumbname);

  unlink("temp-uploads/thumbs/".$thumbname); //Delete Thumbnail.

  $thumbpath = s3url.$s3_thumbpath;

  } else {
  $thumbpath = 0;
  }


  unlink("temp-uploads/".$newname); //Delete Uploaded File.
}

上传到S3函数为:

$s3Client = new S3Client([
  'version'     => 'latest',
  'region'      => 'us-east-2',
  'credentials' => [
     'key'    => s3key,
     'secret' => s3secret,
   ],
]);

$result = $s3Client->putObject([
  'Bucket' => 'bucketname',
  'Key' => $filename,
  'SourceFile' => $filepath,
]);

快速查看文档表明上传是异步的:

https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_promises.html

而且您可能应该使用承诺来创建一个回调,您可以在其中取消link 您的文件。 link.

中有大量代码示例

这个 post 帮我解决了这个问题:

具体来说,我必须使用 fopen/fclose 并使用 Body 而不是 SourceFile

上传