php - PHP检查图像文件是否存在然后将其保存到文件夹
问题描述
我的表中有一个来自外部源的图像列表,我想将所有图像文件保存在本地某个文件夹中。
我最终得到以下代码:
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."; }
}
推荐阅读
- python - Django formview form_valid,表单没有属性`instance`
- r - 将循环应用于 r 中的列表列表
- reactjs - TypeError:无法读取 ReactJS 表单字段中未定义的属性“名称”
- python-3.x - 调用函数时的变量
- ios - rn-fetch-blob - 对于没有扩展名 pdf 的文件,idownload 无法在 ios 上运行
- rust - 当我知道没有更多对其当前内容的引用时,如何对切片进行变异?
- three.js - Threejs存储和加载相机位置和方向
- docker - 无法使用 Serilog 在 Docker 上启动 .NET Core 3.1 Worker 服务
- lua - 我如何将这 2 个不同的 Lua 脚本合并到一个中?它适用于我的罗技鼠标,我无法组合这 2 个切换脚本
- javascript - 每次用户输入任何内容时,将对象永久存储在浏览器中