一个远程采集接口图片的小小案例

一个远程采集接口图片的小小案例

拾忆
2020-06-28 / 2 评论 / 271 阅读 / 正在检测是否收录...

前言

刚才逛百度的时候看到一个随机图的接口,访问了一下,哇,全是小姐姐,所以果断采集了,顺便把采集源码发出来,让他们的图变成自己的图(/大笑)。话不多说,上代吗

代码

<?php
/**
* 随机图片远程采集案例
* @author **
* @url    http://www.syblog.site
* @time   2020-6-28
*/
header('Content-type: application/json');  
    $url = 'https://api.uomg.com/api/rand.img1'; //接口API,可随意更改
    $path = 'images/';
    $url = url_get($url);
    $filenames = basename($url);   
    $file_c = $path . $filenames;   
        if (file_exists($file_c)) {
            echo json_encode(array('url' => $url, 'filename' => $filenames, 'state' => '202'));
        } else {
            if (download($url, $path)) {
                echo json_encode(array('url' => $url, 'filename' => $filenames, 'state' => '200'));
            } else {
                echo json_encode(array('url' => $url, 'filename' => $filenames, 'state' => '201'));
            }  
}   
function url_get($url) {
            // 获取图片真实地址
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_VERBOSE, true);
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_NOBODY, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            curl_setopt($ch, CURLOPT_AUTOREFERER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            // 下面两行为不验证证书和 HOST,建议在此前判断 URL 是否是 HTTPS
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            // $ret 返回跳转信息
            $ret = curl_exec($ch);
            // $info 以 array 形式返回跳转信息
            $info = curl_getinfo($ch);
   
            // 记得关闭 curl
            curl_close($ch);
            // 跳转后的 URL 信息
            return $info['url'];
}
   
        function download($url, $path = 'images/') {
            //远程下载保存
            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_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            $file = curl_exec($ch);
            curl_close($ch);
            $filename = pathinfo($url, PATHINFO_BASENAME);
            $resource = fopen($path . $filename, 'a');
            fwrite($resource, $file);
            fclose($resource);
            return true;
}
71

评论 (2)

取消