繁体   English   中英

PHP 检查图像文件是否存在,然后将其保存到文件夹

[英]PHP check if image file exists then save it to folder

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

我最终得到以下代码:

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
}

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

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

似乎问题出在第二个 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."; }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM