微信云开发PHP下载云存储的图片本地

<?php
include 'db.php';

if (!isset($_GET['img'])) {
    header("Location:/images/none.jpg");
    exit(0);
}

$img = $_GET['img'];
$imgmd5 = md5($img);

$saveimg = dirname(__FILE__) . "/cloudimg/" . $imgmd5 . ".jpg";

if (!file_exists($saveimg)||filesize($saveimg)==0) {
    $token = gettoken();
    $posturlimg = "https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=$token";
    $postimg = array(
        'env' => 'whzf-sfzc-0gcku8s0208e8eb3',
        'file_list' => array(
            array('fileid' => $img, 'max_age' => 600)
        )
    );
    $getimginfo = post($posturlimg, $postimg); //请求数据	
    $detailimg = json_decode($getimginfo)->file_list;
	//如果下载不了远程下载图片的毛病,直接转发URL。
	//  header("Location:".$detailimg[ 0 ]->download_url);
	// die(); 
	
	//尝试下载 
    try { 
        //$content = file_get_contents($detailimg[ 0 ]->download_url);
 		//file_get_contents下载微信图片不中用
        //使用CURL 直接获取
        $url=$detailimg[ 0 ]->download_url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //https必须设置
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https必须设置
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//如果不是直接打印图片,就要设置此项
        $response = curl_exec($ch);  
        curl_close($ch);
        $fp2=fopen($saveimg,'a');
        fwrite($fp2,$response);
        fclose($fp2);
        unset($response);
        header("Location:/cloudimg/" . $imgmd5 . ".jpg");
        
    } catch (Exception $e) {
        header("Location:".$detailimg[ 0 ]->download_url);
        exit(0);
    }
} else {
    header("Location:/cloudimg/" . $imgmd5 . ".jpg");
}

 
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值