PHP实现远程下载图片与 图片接口定义

案例(全):

1. 图片接口定义   这个在TP框架中

<?php
namespace app\api\controller; 

use think\App;
use think\Db;

class Image
{
public function online() // 定义在线图片接口
{
$data = Db::name('images')->select(); //查询数据库信息

foreach ($data as & $value) {
$value['img'] = request()->domain() . $value['img']; // 遍历数据库中的img字段 并且在前面加上 域名的路径
}

return json($data); //变成json字符串
}
}

 

 2.定义curl_get方法,获取到网址中的对象数据   当时定义微擎中的方法

public static function curl_get($url){ //通过网址链接获取到网址中的 对象
$testurl = $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $testurl);
//參数为1表示数据传输。为0表示直接输出显示。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//參数为0表示不带头文件,为1表示带头文件
curl_setopt($ch, CURLOPT_HEADER,0);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}

 

3.定义download方法实现远程下载保存本地路径 当时定义微擎中的方法


public function download($url) //PHP实现通过连接 下载远程图片保存到本地路径的方法
{
$date = 'images/' . date('Ymd') . '/'; //路径
$path = ATTACHMENT_ROOT . $date; //微擎封装函数ATTACHMENT_ROOT代表当前的全部路径,域名到

if ( !file_exists($path) ) mkdir($path, 0777, true); //判断路径是否存在
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
$ext = pathinfo($url, PATHINFO_EXTENSION );
$filename = md5(microtime(true) . mt_rand(1, 1e9)) . '.' . $ext; //修改文件名字
$resource = fopen($path . $filename, 'a');
fwrite($resource, $file);
fclose($resource);
return $date . $filename;
}

 

 

4.调用curl_get方法 和 download方法 写入到本地数据库  当时定义微擎中的方法

 

public function doWebtest()
{
$res = $this->curl_get('http://tp5.com/api/image/online');//调用curl_get方法(url)
$data =json_decode($res, true); // 把$data换成数组形式
foreach ($data as $value){ //遍历数组$data
$build = [ //定义一个数组,用于写入数据库
'gallery_class'=>'0', //数据库表-gallery_class列
'image' => $this->download($value['img']), //数据库表-image列
'uniacid'=>$this->W['uniacid'], //数据库表-uniacid列
'addtime'=>time() //数据库表-addtime列
];

$result = pdo_insert('ims_lc_cj_gallery',$data=$build,$replace=false);//添加到数据库

var_dump($result); //返回值

// echo '<pre>';
// var_dump($build);
}

}

 

posted @ 2021-01-07 16:33  79524795  阅读(209)  评论(0编辑  收藏  举报