我有一个脚本,把图像,平面图和视频压缩成一个压缩文件,它可以很容易地达到500mb,但大多数时候平均是150mb。zip文件的生成速度非常慢,我不知道为什么。有什么建议可以改进我的脚本吗?
我花了10分钟在服务器上创建了100mb的zip文件。
if( !empty( $files ) ){
$random_nbr = mt_rand(1,5646866662);
$path = 'webroot/img/tmp/' . $random_nbr;
if (!file_exists(\Cake\Core\Configure::read('pathTo') . 'webroot/img/tmp')) {
mkdir(\Cake\Core\Configure::read('pathTo') . 'webroot/img/tmp', 0777, true);
}
$destination = \Cake\Core\Configure::read('pathTo') . $path . '_media.zip';
$media_url = \Cake\Core\Configure::read('websiteUrl') . '/img/tmp/' . $random_nbr . '_media.zip';
$zip = new ZipArchive();
$zip->open( $destination, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE );
// Photos
if (isset($files['photos'])):
foreach( $files['photos'] as $f ){
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
// Original
$parsed_file = $f['original_file'];
$download_file = file_get_contents($parsed_file, false,$context);
$zip->addFromString('photos/original/' . basename($parsed_file), $download_file);
// Web with or without a watermark
$web = $this->Images->state_image(1270, $f['id'], 0, '');
$web = $web->response('jpg');
$zip->addFromString('photos/web/' . $f['name'], $web);
// High Res Web with or without a watermark
$web = $this->Images->state_image(2000, $f['id'], 0, '');
$web = $web->response('jpg');
$zip->addFromString('photos/high_res_web/' . $f['name'], $web);
}
endif;
// Floor Plan
if (isset($files['floorplan'])):
foreach( $files['floorplan'] as $f ){
$parsed_file = $f['original_file'];
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$download_file = file_get_contents($parsed_file, false,$context);
$zip->addFromString('floorplan/' . basename($parsed_file), $download_file);
}
endif;
// Video
if (isset($files['video'])):
foreach( $files['video'] as $f ){
$parsed_file = $f['original_file'];
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$download_file = file_get_contents($parsed_file, false,$context);
$zip->addFromString('floorplan/' . basename($parsed_file), $download_file);
}
endif;
$zip->close();
echo $media_url;
die();
}发布于 2018-02-05 12:33:13
除了专用硬件之外,您可能无法做太多事情来加速实际的压缩过程。您可以尝试使用系统zip实用程序来执行exec(),而不是使用PHP来执行此操作,但这可能不会改变事情。
您可以做的(如果主机允许的话)是后台进程,并提供一个状态页面,这样用户就可以看到他们的文件准备好需要多长时间。对于类似的问题,我以前也这样做过。
我所做的是在数据库中有一个表,该表将存储有关要创建的zip文件的信息,以及要添加到zip文件中的所有文件的列表。然后,我使用新创建的数据库记录的ID执行一个后台脚本。
后台进程将读取DB以获取所有详细信息,并开始创建zip文件。它会定期使用完成百分比更新数据库。完成后,它将使用新生成的zip文件的文件系统路径更新DB。
然后,我为终端用户创建了另一个显示进度条的页面。页面会定期向服务器发出Ajax请求,以获取文件的新完成百分比,并相应地更新条形图。当文件完成时,它将更改为下载链接,以便他们开始下载文件。
还有另一个cron作业进程,它会定期检查并删除超过5天的所有临时文件。如果用户再次需要该文件,他们必须重新生成该文件。
https://stackoverflow.com/questions/48575424
复制相似问题