处理大文件或多个文件时 file_put_contents 太慢

2024-04-24

我在用文件放置内容创建视频文件。问题是速度和性能。创建平均大小为 50 mb 的文件平均需要大约 30 到 60 分钟,而且这还只是一个文件。我正在解码字节数组以创建文件。如何提高速度和性能?

$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$Video = $json_obj->Video;
$CAF = $json_obj->CAF;
$Date = $json_obj->Date;
$CafDate = date("Y-m-d", strtotime($Date));

$video_decode = base64_decode($Video);
$video_filename = __DIR__ . '/uploads/'. $CAF . '_'.$CafDate.'_VID.mp4';
$video_dbfilename = './uploads/'. $CAF . '_'.$CafDate.'_VID.mp4';
$save_video = file_put_contents($video_filename, $video_decode);

当您无法预见大小或要处理大文件时,不应将整个文件加载到内存中。最好分块读取文件并逐块处理它。

这是一个关于如何实现它的快速而简单的示例:

<?php
// open the handle in binary-read mode
$handle = fopen("php://input", "r");

// open handle for saving the file
$local_file = fopen("path/to/file", "w");

// create a variable to store the chunks
$chunk = '';

// loop until the end of the file
while (!feof($handle)) {
  // get a chunk
  $chunk = fread($handle, 8192);

  // here you do whatever you want with $chunk
  // (i.e. save it appending to some file)
  fwrite($local_file, $chunk);
}

// close handles
fclose($handle);
fclose($local_file);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

处理大文件或多个文件时 file_put_contents 太慢 的相关文章

随机推荐