PHP工具函数(LTS)

摘要:汇总一些常用的工具函数

#### PHP发送Json对象数据

/**
* PHP发送Json对象数据
*
* @param $url 请求url
* @param $jsonStr 发送的json字符串
* @return array
*/
    public function http_post_json($url,$jsonStr)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        return array($httpCode,$response);
    }

 ####判断请求方式

        if($_SERVER['REQUEST_METHOD'] !='GET')

####检查一个变量是否是邮箱

/**
 * 检查一个变量是否是邮箱
 * @param   mixed   $param  待检测的字符串
 * @return  bool
 */
function is_email($param)
{
    return (bool) preg_match('/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i', $param);
}

####检查一个变量是否是 IP 地址

/**
 * 检查一个变量是否是 IP 地址
 * @param   mixed   $param  待检测的字符串
 * @return  bool
 */
function is_ip($param)
{
    return (bool) preg_match('/^\d+\.\d+\.\d+\.\d+$/', $param);
}

####检查一个变量是否是身份证号码

/**
 * 检查一个变量是否是身份证号码
 * @param   mixed   $param  待检测的字符串
 * @return  bool
 */
function is_id($param)
{
    return (bool) preg_match('/^\d{15}|\d{18}$/', $param);
}

/**
 * 检查一个变量是否是邮编
 * @param   mixed   $param  待检测的字符串
 * @return  bool
 */
function is_zip($param)
{
    return (bool) preg_match('/^\d{6}$/', $param);
}

/**
 * 检查一个变量是否是 QQ
 * @param   mixed   $param  待检测的字符串
 * @return  bool
 */
function is_qq($param)
{
    return (bool) preg_match('/^[1-9][0-9]{4,}$/', $param);
}

/**
 * 检查一个变量是否是手机号码
 * @param   mixed   $param  待检测的字符串
 * @return  bool
 */
function is_mobile($param)
{
    return (bool) preg_match('/^1(3|4|5|6|7|8|9)[0-9]{1}\d{8}$/', $param);
}

/**
 * 检查是否是有效的7~8位的电话
 * @param $param
 * @return bool
 */
function is_telphone($param)
{
    return (bool) preg_match('/^\d{7,8}$/', $param);
}

/**
 * 检查是否是有效的验证码
 * @param $param
 * @return bool
 */
function is_code($param)
{
    return (bool) preg_match('/^\d{4}$/', $param);
}

/**
 * 检查一个变量是否是数字,且长度是否超过最大长度
 * @param    string    $val    待检测的字符串
 * @param    int       $length 最大长度
 * @return   bool
 */
function is_int_strlen($val, $length)
{
    // 如果最大长度为1 则变量不允许为0
    if ($length == 1) {
        return (bool) preg_match('/^[1-9]$/', $val);
    } else {
        return (bool) preg_match('/^[0-9]\\d{0,'.($length-1).'}$/', $val);
    }
}

/**
 * 获取外部ip
 */

function get_ip(){
  $ip=false;
  if(!empty($_SERVER["HTTP_CLIENT_IP"])){
    $ip = $_SERVER["HTTP_CLIENT_IP"];
  }
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
    if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
    for ($i = 0; $i < count($ips); $i++) {
      if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
        $ip = $ips[$i];
        break;
      }
    }
  }
  return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}


/**
 * 简单对称加密算法之加密
 * @param String $string 需要加密的字串
 * @param String $skey 加密EKY
 * @author Anyon Zou <zoujingli@qq.com>
 * @date 2013-08-13 19:30
 * @update 2014-10-10 10:10
 * @return String
 */
function encode($string = '', $skey = 'cxphp') {
    $strArr = str_split(base64_encode($string));
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value)
        $key < $strCount && $strArr[$key].=$value;
    return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}
/**
 * 简单对称加密算法之解密
 * @param String $string 需要解密的字串
 * @param String $skey 解密KEY
 * @author Anyon Zou <zoujingli@qq.com>
 * @date 2013-08-13 19:30
 * @update 2014-10-10 10:10
 * @return String
 */
function decode($string = '', $skey = 'cxphp') {
    $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value)
        $key <= $strCount  && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
    return base64_decode(join('', $strArr));
}

                        
/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 (单位:秒)
 * @return string
 */
function think_ucenter_encrypt($data, $key, $expire = 0) {
    $key  = md5($key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char =  '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x=0;
        $char  .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data,$i,1)) + (ord(substr($char,$i,1)))%256);
    }
    return str_replace('=', '', base64_encode($str));
}

/**
 * 系统解密方法
 * @param string $data 要解密的字符串 (必须是think_encrypt方法加密的字符串)
 * @param string $key  加密密钥
 * @return string
 */
function think_ucenter_decrypt($data, $key){
    $key    = md5($key);
    $x      = 0;
    $data   = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data   = substr($data, 10);
    if($expire > 0 && $expire < time()) {
        return '';
    }
    $len  = strlen($data);
    $l    = strlen($key);
    $char = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char  .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}
                        
                        
                        
                        

/**
* 获取当前IP
* @return string
*/
    public static function get_ip()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return($ip);
    }
/**
 * 去除内容中的特数字符
 *
 * @param $text
 * @return mixed|string
 */
public static function format_text($text)
{
    try{
        $text = preg_replace('#(\s)#', '', $text);
        $text = trim($text);
        $text = str_replace(' ', '', $text);
        $text = str_replace('"', "'", $text);
        $text = str_replace('<br>', "", $text);
        return $text;
    }catch (Throwable $e) {
        Logs::write($e->getMessage(),'gsx');
    }
}
/**
 * 格式化用户组(标签)名
 *
 * @param $name
 * @return mixed
 */
public static function formatting_label_name($name)
{
    try{
        $name = trim($name);
        $name = str_replace('-','',$name);
        $name = str_replace('-','',$name);
        $name = str_replace(',','',$name);
        $name = str_replace(',','',$name);
        $name = str_replace(' ','',$name);
        $name = str_replace(' ','',$name);
        return $name;
    }catch (Throwable $e) {
        Logs::write($e->getMessage(),'gsx');
    }
}
  /*
   * 多维转一维 php5.5版本支持
  */
    public static function array_to_cloumn($data,$cloumn_value,$cloumn_key='')
    {
        $newdata=array();
        if(empty($cloumn_key))
        {
            foreach ($data as $key => $item) {
                $newdata[]=$item[$cloumn_value];
            }
        }
        else
        {
            foreach ($data as $key => $item) {
                $newdata[$item[$cloumn_key]]=$item[$cloumn_value];
            }
        }
        return $newdata;
    }
/**
 * CURL POST
 *
 * @param $name
 * @return mixed
 */
    public static function Curl_Post($url,$param,$is_json=false){
            $oCurl = curl_init();
            if(stripos($url,"https://")!==FALSE){
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
            }

            curl_setopt($oCurl, CURLOPT_URL, $url);
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($oCurl, CURLOPT_POST,true);
            curl_setopt($oCurl, CURLOPT_POSTFIELDS,$param);
            if($is_json){
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array(
                        'Content-Type: application/json',
                        'Content-Length: '.strlen($param)));
                }

            $sContent = curl_exec($oCurl);
            curl_close($oCurl);
            return $sContent;

           }

/**
 * CURL GET
 *
 * @param $name
 * @return mixed
 */
    public static function Curl_Get($url)
    {
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        curl_close($oCurl);
        //var_dump($sContent);
        return $sContent;

    }

    //https请求(支持GET和POST)
    public static function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * Curl_request 代替 file_get_contents
     * @param $url
     * @param null $data
     * @return mixed
     */
    public static function https_request( $url, $data = null ) 
    {
        $curl = curl_init();
        curl_setopt( $curl, CURLOPT_URL, $url );
        curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, false );
        if ( !empty( $data ) ) {
            curl_setopt( $curl, CURLOPT_POST, 1 );
            curl_setopt( $curl, CURLOPT_POSTFIELDS, $data );
        }
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
        $output = curl_exec( $curl );
        $status = curl_getinfo( $curl );
        //失败尝试重连
        $times = 2;
        while ( isset( $status ) && $status[ 'http_code' ] != 200 && $times > 0 ) {
            $output = curl_exec( $curl );
            $status = curl_getinfo( $curl );
            $times--;
        }
        //还有错误提交日志
        if ( curl_errno( $curl ) ) {
            $error_num = sprintf( 'Curl error message: %s, error no: %s, url: %s, params: %s, output: %s.', curl_error( $curl ), curl_errno( $curl ), $url, var_export( $data, true ), var_export( $output, true ) );
            Logs::write($error_num, 'fatal_');
        }
        @curl_close( $curl );
        return $output;
    }


/**
* 对二维数组进行排序
* @param $array
* @param $keyid 排序的键值
* @param $order 排序方式 'asc':升序 'desc':降序
* @param $type  键值类型 'number':数字 'string':字符串
*/
    function sort_array(&$array, $keyid, $order = 'asc', $type = 'number') {
        if (is_array($array)) {
            foreach($array as $val) {
                $order_arr[] = $val[$keyid];
            }

            $order = ($order == 'asc') ? SORT_ASC: SORT_DESC;
            $type = ($type == 'number') ? SORT_NUMERIC: SORT_STRING;

            array_multisort($order_arr, $order, $type, $array);
        }
    }
    //@sort_array($list, $get['sort'], $get['order'], "string");

/*
 *多维数组查找
 */
    public static function array_search_multi($arr,$column,$findstring){
            foreach ($arr as $key=>$value){
                if($value[$column]==$findstring)
                    return $value;
            }
            return false;
    }

    public static function array_search_multi_datas($arr,$column,$findstring){
        $res=array();
        foreach ($arr as $key=>$value){
            if($value[$column]==$findstring)
                $res[]=$value;
        }
        return $res;
    }

    //查找数组$deviceslist中ip字段为值$dst_ip,返回该字段的数组
    //调用:$ret=$this->array_search_multi($deviceslist,"ip",$dst_ip);

     /*
    *二维数组的去重操作
    */
    public static function unique_arr($array2D,$stkeep=false,$ndformat=true) {
        // 判断是否保留一级数组键 (一级数组键可以为非数字)
        if($stkeep) $stArr = array_keys($array2D);
        // 判断是否保留二级数组键 (所有二级数组键必须相同)
        if($ndformat) $ndArr = array_keys(end($array2D));
        //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        foreach ($array2D as $v){
            $v = join(",,,",$v);
            $temp[] = $v;
        }
        //去掉重复的字符串,也就是重复的一维数组
        $temp = array_unique($temp);
        //再将拆开的数组重新组装
        foreach ($temp as $k => $v) {
        if($stkeep) $k = $stArr[$k];
            if($ndformat) {
                $tempArr = explode(",,,",$v);
                foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval;
            }else $output[$k] = explode(",,,",$v);
        }
        return $output;
    }
       //调用:$datas = $this->unique_arr($datas,true);

    /**
     * 取得当前URL
     * @author 
     * @return [type] [description]
     */
    public static function get_url() {
        //脚本的时候不显示
        if (! isset($_SERVER["SERVER_PORT"])) {
            return '';
        }

        $port = $_SERVER["SERVER_PORT"] != '80' ? ':' . $_SERVER["SERVER_PORT"] : '';
        $sys_protocal = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] . $port : '') . $relate_url;
    }

    /**
     * 取得当前时间的当前月的第一天,最后一天
     * @author wuzhengping 
     * @param  [type] $date [description]
     * @return [type]       [description]
     */
    public static function get_month_days($date = '') 
    {
        $date = $date ?: date('Y-m-d');

        $firstday = date("Y-m-01", strtotime($date));
        $lastday = date("Y-m-d", strtotime("$firstday +1 month -1 day"));
        return [$firstday, $lastday];
     }

    /**
      * 取得当前时间的上个月的第一天,最后一天
      * @author wuzhengping 
      * @param  [type] $date [description]
      * @return [type]       [description]
      */
    public static function get_last_month_days($date = '') 
    {
        $date = $date ?: date('Y-m-d');

        $timestamp = strtotime($date);
        $firstday=date('Y-m-01', strtotime(date('Y', $timestamp) . '-' . (date('m',$timestamp)-1) . '-01'));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
        return [$firstday, $lastday];
     }

    /**
      * 取得当前时间的下个月的第一天,最后一天
      * @author wuzhengping
      * @param  [type] $date [description]
      * @return [type]       [description]
      */
    public static function get_next_month_days($date) 
   {
        $date = $date ?: date('Y-m-d');

        $timestamp = strtotime($date);
        $arr = getdate($timestamp);
        if ($arr['mon'] == 12){
            $year = $arr['year'] +1;
            $firstday=$year.'-01-01';
        }
        else {
            $firstday=date('Y-m-01', strtotime($arr['year'] . '-' . ($arr['mon']+1) . '-01'));
        }

        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));

        return [$firstday, $lastday];
    }

    /**
     * 是否在繁忙时段
     * @author wuzhengping 
     * @return boolean [description]
     */
    public static function isDuringBusyHours() 
    {
        // 非生产环境
        if (APP_DEBUG OR constant('IS_TEST')) {
            return false;
        }

        $week = date('w');
        $hour = date('H:i');
        if ($week == 3 && ($hour > '11:30' && $hour < '13:00')) {
          return true;
        }
        return false;
    }
    /**
     * 判断是否又汉字和特殊符号
     *
     * @param $mobile
     * @return bool
     */
    public static function drop_all_symbol($mobile)
    {
        try{
            $mobile = $mobile;
            //todo utf8下汉字
            $a = preg_match("/[\x{4e00}-\x{9fa5}]/u",$mobile);
            // 匹配汉子和数字 preg_match_all("/[\x{4e00}-\x{9fa5}]|[0-9]/u",$v['content'],$match);
            if($a){
                return true;
            }
            //todo 匹配特殊字符
            $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
            $b = preg_match($regex,$mobile);
            if($b){
                return true;
            }
            if(strlen($mobile) != 11){
                return true;
            }
            return false;
        }catch (Throwable $e){
            Logs::write($e->getMessage(),'gsx');
        }
    }

    /**
     * 格式化编码
     *
     * @param $text
     * @return mixed|string
     */
    public static function format_code($text)
    {
        try{
            if( !empty($text) ){
                $fileType = mb_detect_encoding($text , ['UTF-8','GBK','LATIN1','BIG5']) ;
                if( $fileType != 'UTF-8'){
                    $text = mb_convert_encoding($text ,'utf-8' , $fileType);
                }
            }
            return $text;
        }catch (Throwable $e){
            Logs::write($e->getMessage(),'gsx');
        }
    }

    /**
     * 判断url的返回状态吗
     */
    public static function check_static_status()
    {
                    $title = get_the_title();
            $domain = $_SERVER['SERVER_NAME'];
            $title = strstr($title, ' (', TRUE);
            $title = str_replace(' ','-',$title);
            $curl = curl_init();
            $url='http://'.$domain.'/Public/html/'.$title.'-msds.html';
            curl_setopt($curl, CURLOPT_URL, $url); //设置URL  
            curl_setopt($curl, CURLOPT_HEADER, 1); //获取Header  
            curl_setopt($curl, CURLOPT_NOBODY, true); //Body就不要了吧,我们只是需要Head  
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //数据存到成字符串吧,别给我直接输出到屏幕了  
            $data = curl_exec($curl); //开始执行啦~  
            $return = curl_getinfo($curl, CURLINFO_HTTP_CODE); //我知道HTTPSTAT码哦~            
            curl_close($curl); //用完记得关掉他            
            return $return;
    }
//英文名首字母大写
function initials($name)
{ 
  $nword = explode(" ",$name); 
  foreach($nword as $letter){ 
    $new_name .= $letter{0}.'.'; 
  } 
  return strtoupper($new_name); 
} 

/**
 * ip转成省市区
 * @param string $ip 传入的ip
 * @return 返回一个包含省市区的数组
 */
function ipToCity($ip = ''){
    if(empty($ip)){
        return '请输入IP地址';
    }
    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    if(empty($res)){ return false; }
    $jsonMatches = array();
    preg_match('#\{.+?\}#', $res, $jsonMatches);
    if(!isset($jsonMatches[0])){ return false; }
    $json = json_decode($jsonMatches[0], true);
    if(isset($json['ret']) && $json['ret'] == 1){
        $json['ip'] = $ip;
        unset($json['ret']);
    }else{
        return false;
    }
    return $json;
}


/*
* 一次性读取全部读取CSV
*/
    <?php 
    $file = fopen('windows_2011_s.csv','r'); 
    while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容
    //print_r($data); //此为一个数组,要获得每一个数据,访问数组下标即可
    $goods_list[] = $data;
     }
    //print_r($goods_list);
    /* foreach ($goods_list as $arr){
        if ($arr[0]!=""){
            echo $arr[0]."<br>";
        }
    } */
     echo $goods_list[2][0];
     fclose($file);
    ?>
/*
* 读取CSV某一行
*/
    <?php
    function get_file_line( $file_name, $line ){
      $n = 0;
      $handle = fopen($file_name,'r');
      if ($handle) {
        while (!feof($handle)) {
            ++$n;
            $out = fgets($handle, 4096);
            if($line==$n) break;
        }
        fclose($handle);
      }
      if( $line==$n) return $out;
      return false;
    }
    echo get_file_line("windows_2011_s.csv", 10);
    ?>
/*
* 读取CSV指定行数(行区间)
*/
<?php
function get_file_line( $file_name, $line_star,  $line_end){
    $n = 0;
    $handle = fopen($file_name,"r");
    if ($handle) {
        while (!feof($handle)) {
            ++$n;
            $out = fgets($handle, 4096);
            if($line_star <= $n){
                $ling[] = $out;
            }
            if ($line_end == $n) break;
        }
        fclose($handle);
    }
    if( $line_end==$n) return $ling;
    return false;
}
$aa = get_file_line("windows_2011_s.csv", 11, 20);  //从第11行到第20行
foreach ($aa as $bb){
    echo $bb."<br>";
}
?>

        ### 判断文件状态码
                    $show_title = get_the_title();
            }
            $show_title = $title;
            $title = str_replace(' ','-',$title);
            $curl = curl_init();
            $url='http://'.$domain.'/Public/html/'.$title.'-msds.html';
            curl_setopt($curl, CURLOPT_URL, $url); //设置URL  
            curl_setopt($curl, CURLOPT_HEADER, 1); //获取Header  
            curl_setopt($curl, CURLOPT_NOBODY, true); //Body就不要了吧,我们只是需要Head  
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //数据存到成字符串吧,别给我直接输出到屏幕了  
            $data = curl_exec($curl); //开始执行啦~  
            $return = curl_getinfo($curl, CURLINFO_HTTP_CODE); //我知道HTTPSTAT码哦~            
            curl_close($curl); //用完记得关掉他 
            if($return == 200){
                ?>


/*
 *   PHP将文件生成压缩包
*/
    $path = "./rili.html";
    $filename = "rili-test.zip";
    $zip = new ZipArchive();
    $zip->open($filename,ZipArchive::CREATE);   //打开压缩包
    $zip->addFile($path,basename($path));   //向压缩包中添加文件
    $zip->close();  //关闭压缩包

    /**
     * 格式化获取当前几周是几年的第几周
     * 
     * @param  [type] $num [description]
     * @return [type]      [description]
     */
    function format_week($num)
    {
        for ($x=0; $x<=$num-1; $x++) {
            $desc_num = $x*7;
            $beginLastweek=mktime(0,0,0,date('m'),date('d')-date('w')+1-$desc_num,date('Y'));
            $endLastweek=mktime(23,59,59,date('m'),date('d')-date('w')+7-$desc_num,date('Y'));
            $return[$x]=date('Y',$beginLastweek).'W'.date('W',$endLastweek);
        } 
        echo '<pre>';
        var_dump($return);
    }
    /**
     * 检查文件的状态(404 200 等用于检查文件是否存在)
     *
     * @param  $fileUrl 文件地址
     * @return mixed
     */
    public function checkFileStatus($fileUrl)
    {
        $curl = curl_init();
        $url_pdf=$fileUrl;
        curl_setopt($curl, CURLOPT_URL, $url_pdf);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//一下避免SSL验证,防止ssl服务端验证失败
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,false);
        $data_pdf = curl_exec($curl);
        $return_pdf = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        //$return_pdf .= $file_target_pdf_url;
        curl_close($curl);
        return $return_pdf;
    }

使用CURL发送附件

    public function postJson($url,$jsonStr,$filePath,$fileName)
    {
        $cfile = curl_file_create($filePath, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $fileName);
        $jsonStr['FileData0']= $cfile;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($httpCode,$response);
    }
评论
  • 2020-05-11 13:03:15 by Eric Guo
    $cfile = curl_file_create('F:/url.txt','','url.txt'); $jsonStr['cfile']= $cfile; 可用于php后台发送附件信息
  • 2020-02-28 14:38:57 by Eric-上海奥深商务咨询有限
    尤其是https的
  • 2020-02-28 14:38:39 by Eric-上海奥深商务咨询有限
    Curl_Post 这个发送post比较好
  • 2019-09-19 14:58:25 by Eric Guo
    mysql_real_escape_string 比addslashes强大,可以使用这个
  • 2019-06-26 14:04:24 by Eric Guo
    addslashes() 给预定义字符前面加反斜杠,防止单引号等被转义