<?php
namespace Smi\Controller;
use Think\Controller;

/**
 * curl控制器获取接口数据
 */
class CurlController extends Controller
{
    /**
     * [get_curl description]
     * @param  [type] $json   [传递的数据]
     * @param  [type] $url    [访问的接口地址]
     * @param  [type] $second [超时时间]
     * @return [type]         [正常返回结果错误返回false]
     */
    public static function get_curl($json,$url,$second=30)
    {
        $type = 'get';
        $arr = json_decode($json, true);

        //拼接字符串
        $url .= '?';
        foreach ($arr as $key => $value) {
            $url .= '&'.$key.'='.$value;
        }

        //执行并返回数据
        $ch = self::curl('', $url,$second,$type);
        $ret = curl_exec($ch);
        if ($ret) {
            curl_close($ch);
            return $ret;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return FALSE;
        }
    }

    /**
     * POST方式
     * @param  [type]  $json   [传递的数据]
     * @param  [type]  $url    [访问的接口地址]
     * @param  integer $second [超时时间]
     * @return [type]          [正常返回结果错误返回false]
     */
    public static function post_curl($json,$url,$second=30)
    {
        //执行并返回数据
        $ch = self::curl($json,$url,$second);
        $ret = curl_exec($ch);
        if ($ret) {
            curl_close($ch);
            return $ret;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return FALSE;
        }
    }

    /**
     * curl
     * @param  string  $json   [传递的数据]
     * @param  [type]  $url    [访问的接口地址]
     * @param  integer $second [超时时间]
     * @param  string  $type   [调用类型-post/get]
     * @return [type]          [curl权柄]
     */
    public static function curl($json='',$url,$second=30,$type='post')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置超时
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        if ($type==='post') {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        }

        return $ch;
    }
}