PHP 封装函数

<?php

    /**
 * ==============================================================================
 * 功 能:公共封装函数
 * 版 权:Copyright © 成都**科技有限责任公司
 * @Author luop <805500101@qq.com>
 * @Created on 2019/10/29 11:38
 * ==============================================================================
 *
 * -< 修改履历 >----------------------------------------------
 * 1  V1.00  2019/10/29 8:49 创建
 *
 * Created by PhpStorm.
 */
//=================================== 目录 start =================================//
/**
 * 1. 获取时间类
 * 2. 身份证操作
 * 3. 判断类
 * 4. 请求类
 * 5. 其他
*/
//=================================== 目录 end =================================//

/****************************************1. 获取时间类********************************************/

/**
 * 1.获取当月开始和结束
 * @Author: luop <805500101@qq.com>
 * @Interface getthemonth
 * @Date 2019/10/29 8:47
 * @param string $date  时间戳
 * @return array
 */
function getthemonth($date)
{
    $firstday = date('Y-m-01 00:00:00', $date);
    $lastday = date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day"));
    return array('firstday'=>$firstday,'lastday'=>$lastday);
}

/**
 * 时间判断 中文显示
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:20
 * @param string $str_in 传入时间或时间戳
 * @param bool $strtotime 是否是普通时间
 * @return false|string
 */
function IsTodayOrTomorrow($str_in,$strtotime = false){

    $str_today = date('Y-m-d'); //获取今天的日期 字符串
    $ux_today =  strtotime($str_today); //将今天的日期字符串转换为 时间戳

    $ux_tomorrow = $ux_today+3600*24;// 获取明天的时间戳
    $str_tomorrow = date('Y-m-d',$ux_tomorrow);//获取明天的日期 字符串

    $ux_afftertomorrow = $ux_today+3600*24*2;// 获取后天的时间戳
    $str_afftertomorrow = date('Y-m-d',$ux_afftertomorrow);//获取后天的日期 字符串

    if(!$strtotime){
        $str_in_format = $str_in;
    }else{
        $ux_in = strtotime($str_in);//获取输入日期的 时间戳
        $str_in_format = date('Y-m-d',$ux_in);//格式化为y-m-d的 日期字符串
    }

    if($str_in_format==$str_today){
        return "今天";
    }else if($str_in_format==$str_tomorrow){
        return "明天";
    }else if($str_in_format==$str_afftertomorrow){
        return "后天";
    }else{
        return   $str_in_format;
    }
}

/**
 * 获取当前星期
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 11:20
 * @param string $date 普通日期
 * @return mixed
 */
function week($date,$affix='星期') {
    if(isset($date) && $date > 10){
        $timestamp = strtotime($date);
        $times = intval($timestamp);
        $index = date("w",$timestamp);
        if(!$times) return '';
    }else{
        $index = $date;
    }

    $weekarray = array('日','一','二','三','四','五','六');
    return $affix.$weekarray[$index];
}

/**
 *  获取一月或一年或一周的日期期间
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 11:20
 * @param string $date 普通日期
 * @param string $type m月w周y年
 * @return array();
 */
function Week_arr($date='',$type="m"){
    if($type == "m"){
        //当前日期
        $firstday = date("Y-m-01",strtotime($date));
        $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
        return array('start'=>$firstday,'end'=>$lastday);

    }elseif($type="w"){
        //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $first=1;
        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $w=date('w',strtotime($date));
        //获取本周开始日期,如果$w是0,则表示周日,减去 6 天
        $week_start=date('Y-m-d',strtotime("$date -".($w ? $w - $first : 6).' days'));
        //本周结束日期
        $week_end=date('Y-m-d',strtotime("$week_start +6 days"));
        return array('start'=>$week_start,'end'=>$week_end);
    }else{
        $begin_this_year=date('Y-01-01 00:00:00');
        $end_this_year=date('Y-12-31 23:59:59');
        return array('start'=>$begin_this_year,'end'=>$end_this_year);
    }
}

/**
 * 时间比较函数,返回两个日期相差几秒、几分钟、几小时或几天
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 11:20
 * @param $date1
 * @param $date2
 * @param string $unit
 * @return bool|float
 *
 */
function getDateDiff($date1 = '', $date2 = '', $unit = "i") { //时间比较函数,返回两个日期相差几秒、几分钟、几小时或几天
    switch ($unit) {
        case 's':
            $dividend = 1;
            break;
        case 'i':
            $dividend = 60;
            break;
        case 'h':
            $dividend = 3600;
            break;
        case 'd':
            $dividend = 86400;
            break;
        default:
            $dividend = 86400;
    }
    $time1 = strtotime($date1 ? $date1 : date('Y-m-d H:i:s', time()));
    $time2 = strtotime($date2 ? $date2 : date('Y-m-d H:i:s', time()));
    if ($time1 && $time2)
        return (float)($time1 - $time2) / $dividend;
    return false;
}

/**
 * 按分钟数计算出几小时几分钟前
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 11:20
 * @param $secs
 * @return string
 */
function secsToStr($secs,$lx = false) {
    $r = '';
    /*if($secs>=86400){$days=floor($secs/86400);
        $secs=$secs%86400;
        $r=$days.' 天';
        if($days<>1){$r.='s';}
        if($secs>0){$r.=', ';}}*/
    if($secs >= 60 || $lx==true){
        $hours=floor($secs/60);
        $secs=$secs%60;
        $r.=$hours.' 小时';
        /*if($secs>0){
            $r.=',';
        }*/
    }
    /*if($secs>=60){$minutes=floor($secs/60);
        $secs=$secs%60;
        $r.=$minutes.' 秒';
        if($minutes<>1){$r.='s';}
        if($secs>0){$r.=', ';}}*/
    if($secs>1)
        $r.=$secs.' 分钟';
    return $r;
}

/**
 * 时间区间判断
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 11:20
 * @param $start_time
 * @param string $end_time
 * @return bool|float
 */
function getTimeDiff($start_time,$end_time = ''){
    $_t = explode('-',$start_time);
    $_t = isset($_t[0]) ? $_t[0] : 0;
    $_time = date('Y-m-d', time()) . ' '.$_t.':00';
    return getDateDiff($_time, $end_time ? $end_time : date('Y-m-d H:i:s', time()));
}

/****************************************2. 身份证操作********************************************/

/**
 * 获取身份证性别
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 11:20
 * @param string $cid 身份证
 * @return string
 */
function get_xingbie($cid) { //根据身份证号,自动返回性别
    if (!isIdCard($cid)) return '';
    $sexint = (int)substr($cid,16,1);

    return $sexint % 2 === 0 ? '女' : '男';
}

/**
 * 获取身份号是否正确
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 11:20
 * @param string $number 身份证
 * @return bool
 */
function isIdCard($number) { // 检查是否是身份证号
    // 转化为大写,如出现x
    $len = strlen($number)-1;
    $number = strtoupper($number);
    //加权因子
    $wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    //校验码串
    $ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    //按顺序循环处理前17位
    $sigma = 0;
    for ($i = 0;$i < $len;$i++) {
        //提取前17位的其中一位,并将变量类型转为实数
        $b = (int) $number{$i};

        //提取相应的加权因子
        $w = $wi[$i];

        //把从身份证号码中提取的一位数字和加权因子相乘,并累加
        $sigma += $b * $w;
    }
    //计算序号
    $snumber = $sigma % 11;

    //按照序号从校验码串中提取相应的字符。
    $check_number = $ai[$snumber];

    if ($number{$len} == $check_number) {
        return true;
    } else {
        return false;
    }
}

/**
 * 从身份证中提取生日,包括18位和15位身份证
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 11:19
 * @param string $IDCard 身份证
 * @return mixed
 * @Author: luop <805500101@qq.com>
 */
function getIDCardInfo($IDCard){
    $flag = '';
    $tdate= '';
    $result['error']=1;//0:未知错误,1:身份证格式错误,2:无错误
    $result['flag']='';//0:标示成年,1:标示未成年
    $result['tdate']='';//生日,格式如:--
    if(!preg_match("/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/",$IDCard)){
        $result['error']= 1;
        return $result;
    }else{
        if(strlen($IDCard)==18){
            $tyear=intval(substr($IDCard,6,4));
            $tmonth=intval(substr($IDCard,10,2));
            $tday=intval(substr($IDCard,12,2));
            if($tyear>date("Y")||$tyear<(date("Y")-100)){
                $flag=0;
            }elseif($tmonth<0||$tmonth>12) {
                $flag=0;
            } elseif($tday<0||$tday>31) {
                $flag=0;
            }else{
                $tdate=$tyear."-".$tmonth."-".$tday;
                if((time()-mktime(0,0,0,$tmonth,$tday,$tyear))>18*365*24*60*60)
                {
                    $flag=0;
                }
                else
                {
                    $flag=1;
                }
            }
        }elseif(strlen($IDCard) == 15){
            $tyear=intval("19".substr($IDCard,6,2));
            $tmonth=intval(substr($IDCard,8,2));
            $tday=intval(substr($IDCard,10,2));
            if($tyear>date("Y")||$tyear<(date("Y")-100)){
                $flag=0;
            }elseif($tmonth<0||$tmonth>12) {
                $flag=0;
            } elseif($tday<0||$tday>31) {
                $flag=0;
            }else{
                $tdate=$tyear."-".$tmonth."-".$tday;
                if((time()-mktime(0,0,0,$tmonth,$tday,$tyear))>18*365*24*60*60)
                {
                    $flag=0;
                }
                else
                {
                    $flag=1;
                }
            }
        }
    }
    $result['error']=2;//:未知错误,:身份证格式错误,:无错误
    $result['flag'] =$flag;//标示成年,标示未成年
    $result['tdate']=$tdate;//生日日期
    return $result;
}

/**
 * 根据生日获取年龄信息1
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:25
 * @param $birthday
 * @return bool|false|int
 */
function birthday($birthday){
    $age = strtotime($birthday);
    if($age === false) {
        return false;
    }
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
    $now = strtotime("now");
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
    $age = $y2 - $y1;
    if((int)($m2.$d2) < (int)($m1.$d1))
        $age -= 1;
    return $age;
}

/**
 * 出生日期获取年龄2
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:25
 * @param string $birthday 出生年月日
 * @return false|string
 */
function getAge($birthday){
    $birthday = strtotime($birthday);//int strtotime ( string $time [, int $now ] )
    $year = date('Y', $birthday);
    if(($month = (date('m') - date('m', $birthday))) < 0){
        $year++;
    }else if ($month == 0 && date('d') - date('d', $birthday) < 0){
        $year++;
    }
    return date('Y') - $year;
}

/****************************************3. 判断类********************************************/

/**
 * 取得文件扩展
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param $filename //文件名
 * @return string //扩展名
 */
function fileext($filename)
{
    return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

/**
 * 判断email格式是否正确
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param string $email
 * @return string
 */
function is_email($email)
{
    return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

/**
 * 检查密码长度是否符合规定
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param STRING $password
 * @return    TRUE or FALSE
 */
function is_password($password)
{
    $strlen = strlen($password);
    if ($strlen >= 6 && $strlen <= 20) return true;
    return false;
}

/**
 * 检测输入中是否含有错误字符
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param string $string 要检查的字符串名称
 * @return TRUE or FALSE
 */
function is_badword($string)
{
    $badwords = array("\\", '&', ' ', "'", '"', '/', '*', ',', '<', '>', "\r", "\t", "\n", "#");
    foreach ($badwords as $value) {
        if (strpos($string, $value) !== FALSE) {
            return TRUE;
        }
    }
    return FALSE;
}

/**
 * 检查用户名是否符合规定
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param STRING $username 要检查的用户名
 * @return    TRUE or FALSE
 */
function is_username($username)
{
    $strlen = strlen($username);
    if (is_badword($username) || !preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)) {
        return false;
    } elseif (20 < $strlen || $strlen < 2) {
        return false;
    }
    return true;
}

/**
 * IE浏览器判断
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 */
function is_ie()
{
    $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if ((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
    if (strpos($useragent, 'msie ') !== false) return true;
    return false;
}

/****************************************5. 其他********************************************/

/**
 * 2.将Base64图片转换为本地图片并保存
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 8:47
 * @param string [Base64] $image [要保存的Base64]
 * @param string $prePath 传入路径前缀
 * @return String $imageSrc [图片保存路径]
 */
function base64ImageContent($image, $prePath = 'Upload/tmp/signImage/')
{
    $imageName = "25220_" . date("His", time()) . "_" . rand(1111, 9999) . '.png';
    if (strstr($image, ",")) {
        $image = explode(',', $image);
        $image = $image[1];
    }
    $path = $prePath . date("Ymd", time());
    if (!is_dir($path)) { //判断目录是否存在 不存在就创建
        mkdir($path, 0777, true);
    }
    $imageSrc = $path . "/" . $imageName;  //图片名字
    $r        = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
    if (!$r) {
        return false;
        //echo json_encode(['data'=>null,"code"=>1,"msg"=>"图片生成失败"],JSON_UNESCAPED_UNICODE);
    } else {
        return $imageSrc;
        //echo json_encode(['data'=>1,"code"=>0,"msg"=>"图片生成成功"],JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 3.打印
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 8:47
 * @param $var .. 要打印的变量
 */
function pr($var)
{
    $template = PHP_SAPI !== 'cli' ? '<pre>%s</pre>' : "\n%s\n";
    printf($template, print_r($var, true));
}

/**
 * 对用户的密码进行加密
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:30
 * @param string $password 密码
 * @param string $encrypt 传入加密串
 * @return array|string
 */
function password($password, $encrypt = '')
{
    $pwd = array();
    $pwd['encrypt'] = $encrypt ? $encrypt : getStrRand(6);
    $pwd['password'] = md5(md5(trim($password)) . $pwd['encrypt']);
    return $encrypt ? $pwd['password'] : $pwd;
}

/**
 * 返回指定长度随机字符串
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:30
 * @param int $length 长度
 * @return string
 */
function getStrRand($length=6){
    $chars = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand='';
    for($i = 1; $i <= $length; $i++){
        $rand.=$chars[mt_rand(0, strlen($chars)-1)];
    }
    return $rand;
}

/**
 * 产生随机数字字符串
 * (可用于登录生成token)
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:30
 * @param    int $length 输出长度
 * @param    string $chars 可选的 ,默认为 0123456789
 * @return   string     字符串
 */
function random($length, $chars = '0123456789')
{
    $hash = '';
    $max = strlen($chars) - 1;
    mt_srand();
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}
/**
 * 安全过滤函数
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:30
 * @param string $string 输入字符
 * @return string
 */
function safe_replace($string)
{
    $string = str_replace('%20', '', $string);
    $string = str_replace('%27', '', $string);
    $string = str_replace('%2527', '', $string);
    $string = str_replace('*', '', $string);
    $string = str_replace('"', '&quot;', $string);
    $string = str_replace("'", '', $string);
    $string = str_replace('"', '', $string);
    $string = str_replace(';', '', $string);
    $string = str_replace('<', '&lt;', $string);
    $string = str_replace('>', '&gt;', $string);
    $string = str_replace("{", '', $string);
    $string = str_replace('}', '', $string);
    $string = str_replace('\\', '', $string);
    return $string;
}

/**
 * 有道翻译
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param string $content 输入的信息
 * @return mixed
 */
function youdao($content){
    $cache_name = 'youDao:fy:'.$content;
    //配置的缓存
    $cache_tmp = get_cache($cache_name);
    if($cache_tmp){
        return $cache_tmp;
    }
    $url = "http://fanyi.youdao.com/openapi.do?keyfrom=xujiangtao&key=1490852988&type=data&doctype=json&version=1.1&q=".$content;
    $list = file_get_contents($url);
    $js_de = json_decode($list,true);
    if($js_de['errorCode'] == 0){
        if($js_de['query'] == $content){
            return set_cache($cache_name,$js_de['translation'][0],C('tm_lg')*24);
        }else{
            return $js_de['translation'][0];
        }
    }else{
        return $content;
    }
}

/**
 * 获取当前页面完整URL地址
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @return string
 */
function get_url()
{
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
    $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . safe_replace($_SERVER['QUERY_STRING']) : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}

/**
 * 转换字节数为其他单位
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param   string $filesize 字节大小
 * @return  string    返回大小
 */
function sizecount($filesize)
{
    if ($filesize >= 1073741824) {
        $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
    } elseif ($filesize >= 1048576) {
        $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
    } elseif ($filesize >= 1024) {
        $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
    } else {
        $filesize = $filesize . ' Bytes';
    }
    return $filesize;
}

/**
 * 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param mixed $data //条件数组或者字符串
 * @param string $front //连接符
 * @param mixed $in_column //字段名称
 * @return mixed
 */
function to_sqls($data, $front = ' AND ', $in_column = false)
{
    if ($in_column && is_array($data)) {
        $ids = '\'' . implode('\',\'', $data) . '\'';
        $sql = "$in_column IN ($ids)";
        return $sql;
    } else {
        if ($front == '') {
            $front = ' AND ';
        }
        if (is_array($data) && count($data) > 0) {
            $sql = '';
            foreach ($data as $key => $val) {
                $sql .= $sql ? " $front `$key` = '$val' " : " `$key` = '$val' ";
            }
            return $sql;
        } else {
            return $data;
        }
    }
}

/****************************************4. 请求********************************************/

/**
 * 文件下载
 * @Author: luop <805500101@qq.com>
 * @Date 2019/10/29 10:42
 * @param $filepath //文件路径
 * @param $filename //文件名称
 * @return mixed
 */
function file_down($filepath, $filename = '')
{
    date_default_timezone_set('PRC');
    if (!$filename) $filename = basename($filepath);
    if (is_ie()) $filename = rawurlencode($filename);
    $filetype = fileext($filename);
    $filesize = sprintf("%u", filesize($filepath));
    if (ob_get_length() !== false) @ob_end_clean();
    header('Pragma: public');
    header('Last-Modified: ' . date('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: pre-check=0, post-check=0, max-age=0');
    header('Content-Transfer-Encoding: binary');
    header('Content-Encoding: none');
    header('Content-type: ' . $filetype);
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-length: ' . $filesize);
    readfile($filepath);
    exit;
}

//h获取微信s_k oppid
function Wxid_byCode($code){
    //获取配置微信APPID 和  secret
    $appid_sK = $this->config->get('app.wechat_sk');
    //配置appid
    $appid = $appid_sK['appid'];
    //配置appscret
    $secret = $appid_sK['secret'];

    //声明CODE,获取小程序传过来的CODE
    //api接口
    $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
    //$api = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token={$secret}&js_code={$code}&grant_type=authorization_code";

    //发送
    $data_s = httpGet($api);
    if(isset($data_s['session_key']) && $data_s['session_key']){
        return $data_s;
    }else{
        return false;
    }
}

//获取GET请求
function httpGet($url){
    $headerArray =array("Content-type:application/json;","Accept:application/json");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
    $output = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($output,true);
    return $output;
}

//参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
function curl_request($url,$post='',$cookie='', $returnCookie=0){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
    if($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if($returnCookie){
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie']  = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    }else{
        return $data;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值