【发布时间】: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