简体   繁体   中英

PHP check if image file exists then save it to folder

I have a list of images from external sources in my table and i want to save all the image files on some folder locally.

I end up with this code:

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
}

Here is the code that i want to use to check if file exist on folder; if true - do nothing; if false - save it locally

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."; }

}

The problem is, right now the code does not save anyting to folder/img .

What i am doing wrong here? Is there a better way to do this?

Thanks in advance!

PS: slugify() just transform something like Some title here to some-title-here

PS2: $image would return something like folder/img/some-title-here-img-1.png

It seems the problem was with the second foreach.

I have updated the code like this (works like i wanted):

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."; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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