yii2中的全局工具函数

首先我们在项目根目录下创建文件

/utils/function.php

文件内容如下

<?php

function dd($obj)
{
    echo "<pre>";
    var_dump($obj);
    echo "</pre>";
}

function get($url)
{
    //初始化
    $ch = curl_init();
    //设置选项,包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
    // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    //执行并获取HTML文档内容
    $output = curl_exec($ch);

    if($error=curl_error($ch)){  
        return $error;  
    }

    //释放curl句柄
    curl_close($ch);
    return $output;
}

function post($url, $data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // post数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // post的变量
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

第二步,在web/index.php里面添加下面一句话

require (__DIR__.'/../utils/function.php');

下面我们就可以在全局使用这些方法了。

猜你喜欢

转载自blog.csdn.net/zlh13854157321/article/details/52032900
今日推荐