【问题标题】:PHP check if image file exists then save it to folderPHP检查图像文件是否存在然后将其保存到文件夹
【发布时间】:2021-03-29 14:56:09
【问题描述】:

我的表中有一个来自外部来源的图像列表,我想将所有图像文件保存在本地某个文件夹中。

我最终得到了这个代码:

function save_image($image_url, $image_file){
    // takes URL of image and Path for the image as parameter
    $fp = fopen ($image_file, 'w+');              // open file handle

    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
    curl_exec($ch);

    curl_close($ch);                              // closing curl handle
    fclose($fp);                                  // closing file handle
}

这是我想用来检查文件夹中是否存在文件的代码; 如果为真 - 什么也不做;如果为 false - 将其保存在本地

function download_images(){ global $db;
// Extract results into the array $users (and evaluate if there are any results at the same time)..
if ( $query = $db->get_results("SELECT `id`,`title`,`url_image` FROM table") ){

foreach ( $query as $data ){

$image = "folder/img/" .slugify($data->title) . "-img-" .$data->id . ".png";
   
foreach (glob($image) as $file) {
    if (file_exists($file)) { /* nothing */ }
    else { save_image($data->url_image, $image); }
}

}
      
}

else { echo "No data found."; }

}

问题是,现在代码没有将任何内容保存到folder/img

我在这里做错了什么?有没有更好的方法来做到这一点?

提前致谢!

PS:slugify() 只需将 Some title here 之类的东西转换为 some-title-here

PS2:$image 会返回类似folder/img/some-title-here-img-1.png

【问题讨论】:

  • 这或多或少是相同的东西减去我真正需要的部分(检查文件是否已经存在,所以我下次不会覆盖它)。我想我在尝试检查文件是否存在时做错了。
  • 首先要问的一件事 - 您确定您运行的 sql 将生成与远程站点文件夹文件名匹配的文件名列表吗? (因为我没办法检查你的sql连接)

标签: php image file curl data-manipulation


【解决方案1】:

看来问题出在第二个 foreach 上。

我已经更新了这样的代码(像我想要的那样工作):

function download_images(){ global $db;

if ( $query = $db->get_results("SELECT `id`,`title`,`url_image` FROM table") ){

foreach ( $query as $data ){
    
$local_path_image = "folder/" .slugify($data->title) . "-img-" .$data->id . ".png";

if (file_exists($local_path_image)) { /* if exist, do nothing */
echo $local_path_image . ' already exist' . PHP_EOL; }

else if ( !file_exists($local_path_image)) { /* if doesn't exist, call save_image */
save_image($data->url_image, ABSPATH . $local_path_image);
echo $local_path_image . ' was added' . PHP_EOL; }

else { /* nothing */ } }
      
} else { echo "No data found."; }

}

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2012-02-05
    相关资源
    最近更新 更多