使用File_Put_Contents和File_get_Contents上传50,000张图像的最佳方法

问题描述 投票:0回答:2

我有一个包含大约50,000张图像的CSV。在CSV文件中,我为图像的每个名称都有一列,为图像的实际URL地址有一列。该代码清除空格,撇号和逗号,并用破折号替换空格,以便图像名称更易于阅读,并且SEO更友好,因为原始图像名称是字母和数字的组合。

我正在使用的方法是将代码放置在样式表上,因此为了激活它,我转到https://mysite/stylesheet.php。一旦服务器下载了大约600-700张图像,我最终会收到500错误。

在没有超时的情况下将这些50K图像下载到服务器上的最佳方法是什么?不,我没有直接访问服务器的权限,这是Hostgator Cloud Business设置。我已经将PHP内存从256MB增加到1GB,这完全没有帮助。

下面的代码:

<?php
$filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'photo.csv';
$file = fopen($filename, 'r');
while (($line =fgetcsv($file)) !== FALSE)
{
    $name       =   $line[0];
    $url        =   $line[1];
    $str        =   $name;
    $str        =   str_replace(' '  , '-', strtolower($str)); 
    $str        =   str_replace('\'' , '' , $str);
    $str        =   str_replace(',' , '' , $str);   
    $img        =   'mtg/images/'.$str.'.jpg';
    $img_path   =   dirname(__FILE__) . DIRECTORY_SEPARATOR . $img;

    file_put_contents($img_path, file_get_contents($url));   
}
fclose ($file); ?>
php arrays csv file-get-contents file-put-contents
2个回答
0
投票

由于图像的质量,增加限制基本上没有影响。我最终采用了一种不同的方法,即使用了一个插件,该插件会自动重命名通过csv文件上传的图像。


0
投票

您的主机可以在给定的持续时间内和主机内对可以进行的请求数量设置限制吗?如果数量一致,则在给定的持续时间内在下限(600)处停止事务,并继续下一次迭代。您将需要调整每次迭代中处理的文件的时间和数量。

 <?php
   $filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . 
     'photo.csv';
   $file = fopen($filename, 'r');
   while (($line =fgetcsv($file)) !== FALSE)
  {
  // Start time
  $startTime = new DateTime();
  //  Pause duration : when do you want the process to pause
 $pauseDuration = 300; // seconds
  // Batch size : how many transactions in the active queue 
   $batchSize = 600;
  // Stop time
  $stopTime = startTime->add(DateInterval(pauseDuration));

 If(startTime == stopTime) { 
     // update the stoptime 
     sleep(pauseDuration); } else { 

   $name       =   $line[0];
   $url        =   $line[1];
   $str        =   $name;
   $str        =   str_replace(' '  , '-', strtolower($str)); 
   $str        =   str_replace('\'' , '' , $str);
   $str        =   str_replace(',' , '' , $str);   
   $img        =   'mtg/images/'.$str.'.jpg';
   $img_path   =   dirname(__FILE__) . DIRECTORY_SEPARATOR . 
    $img;
   file_put_contents($img_path, file_get_contents($url));   
    }
   fclose ($file); ?>
© www.soinside.com 2019 - 2024. All rights reserved.