美文网首页
常用PHP方法集合

常用PHP方法集合

作者: 魔思科技 | 来源:发表于2018-12-26 15:58 被阅读4次
// curl get请求
function get($url,$par = null){
    // 处理参数
    if($par)$url = $url . "?" . http_build_query($par);
    // 请求头
    $header = [
    ];
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $url);//设置url属性
    // curl_setopt($curl, CURLOPT_HEADER, 1);//设置头文件的信息作为数据流输出
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不验证hosts
    $output = curl_exec($ch);//获取数据
    curl_close($ch);//关闭curl
    return $output;
}

// curl post请求
function post($url,$data = null){
    // 请求头
    $header = [
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    // curl_setopt($curl, CURLOPT_HEADER, 1);//设置头文件的信息作为数据流输出
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不验证hosts
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

// 获取请求头信息
function getallheaders(){
    if (function_exists('getallheaders')) {
        return getallheaders();
    }else{
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[strtolower(substr($name, 5))] = $value;
            }
        }
        return $headers;
    }
}

// 获取标准格式日期
function getDateTime($format = 0,$time = null){
    if(!$time)$time = time();

    switch ($format) {
        case 1:
            return date('Y-m-d',$time);
            break;
        case 2:
            return date('Y-m-d H:i',$time);
            break;
        case 3:
            return date('Y-m',$time);
            break;
        case 4:
            return date('Y',$time);
            break;
        case 6:
            return date('m',$time);
            break;
        case 7:
            return date('d',$time);
            break;
        case 8:
            return date('H:i:s',$time);
            break;
        case 9:
            return date('Y年m月d日',$time);
            break;
        case 10:
            return date('H',$time);
            break;
        default:
            return date('Y-m-d H:i:s',$time);
            break;
    }
}

//获取人性化时间
function formatDate($time){
    try{
        $time = strtotime($time);
    } catch (\Exception $e){
    }
    $t=time()-$time;
    $f=array(
        '31536000'=>'年',
        '2592000'=>'个月',
        '604800'=>'星期',
        '86400'=>'天',
        '3600'=>'小时',
        '60'=>'分钟',
        '1'=>'秒'
    );
    foreach ($f as $k=>$v){
        if (0 !=$c=floor($t/(int)$k)) {
            return $c.$v.'前';
        }
    }
}

// 截取指定长度的字符串(兼容中文),适合utf-8
function reStrLen($str, $len=10, $etc='...'){
    $restr = '';
    $i = 0;
    $n = 0.0;

    //字符串的字节数
    $strlen = strlen($str);
    while(($n < $len) and ($i < $strlen))
    {
        $temp_str = substr($str, $i, 1);

        //得到字符串中第$i位字符的ASCII码
        $ascnum = ord($temp_str);

        //如果ASCII位高与252
        if($ascnum >= 252)
        {
            //根据UTF-8编码规范,将6个连续的字符计为单个字符
            $restr = $restr.substr($str, $i, 6);
            //实际Byte计为6
            $i = $i + 6;
            //字串长度计1
            $n++;
        }
        else if($ascnum >= 248)
        {
            $restr = $restr.substr($str, $i, 5);
            $i = $i + 5;
            $n++;
        }
        else if($ascnum >= 240)
        {
            $restr = $restr.substr($str, $i, 4);
            $i = $i + 4;
            $n++;
        }
        else if($ascnum >= 224)
        {
            $restr = $restr.substr($str, $i, 3);
            $i = $i + 3 ;
            $n++;
        }
        else if ($ascnum >= 192)
        {
            $restr = $restr.substr($str, $i, 2);
            $i = $i + 2;
            $n++;
        }

        //如果是大写字母 I除外
        else if($ascnum>=65 and $ascnum<=90 and $ascnum!=73)
        {
            $restr = $restr.substr($str, $i, 1);
            //实际的Byte数仍计1个
            $i = $i + 1;
            //但考虑整体美观,大写字母计成一个高位字符
            $n++;
        }

        //%,&,@,m,w 字符按1个字符宽
        else if(!(array_search($ascnum, array(37, 38, 64, 109 ,119)) === FALSE))
        {
            $restr = $restr.substr($str, $i, 1);
            //实际的Byte数仍计1个
            $i = $i + 1;
            //但考虑整体美观,这些字条计成一个高位字符
            $n++;
        }

        //其他情况下,包括小写字母和半角标点符号
        else
        {
            $restr = $restr.substr($str, $i, 1);
            //实际的Byte数计1个
            $i = $i + 1;
            //其余的小写字母和半角标点等与半个高位字符宽
            $n = $n + 0.5;
        }
    }

    //超过长度时在尾处加上省略号
    if($i < $strlen)
    {
        $restr = $restr.$etc;
    }

    return $restr;
}

// 匹配是否是超链接
function isUrl($text){
    return preg_match("/^(https:|http:)?\/\//i",$text);
}

// 去除空格
function removeBlank($str){
    $qian=array(" "," ","�","\t","\n","\r");
    $hou=array("","","","","");
    return str_replace($qian,$hou,$str); 
}

// 匹配用户名
function pregUser($text,$min = 1,$max = 8){
    $rule = '/^[a-zA-Z\x{4e00}-\x{9fa5}0-9_]{'.$min.','.$max.'}$/u';
    preg_match($rule,$text,$result);
    return $result;
}

// 匹配手机号码
function pregPN($text){
    $rule  = "/^1\d{10}$/";
    preg_match($rule,$text,$result);
    return $result;
}

// 匹配邮箱
function pregE($text){
    $zhengze = '/^[a-zA-Z0-9][a-zA-Z0-9._-]*\@[a-zA-Z0-9]+\.[a-zA-Z0-9\.]+$/A';
    preg_match($zhengze,$text,$result);
    return $result;
}

// 匹配密码
function pregPW($text,$min = 6,$max = 32){
    $rule = '/^[a-zA-Z0-9_]{'.$min.','.$max.'}$/';
    preg_match($rule,$text,$result);
    return $result;
}

// 获取简介
function getDescribe($str, $len=150, $etc='...'){
    $str = htmlspecialchars_decode($str);//html转义
    $str = strip_tags($str);//去掉html标签
    $str = removeBlank($str);//自定义 去除空格方法
    return reStrLen($str,$len,$etc);//自定义 截取指定长度的字符串方法
}

// 处理datePicker时间
function datePicker($datetime){
    $datetime = explode(' ',$datetime);
    $datetime = array_slice($datetime,0,6);
    $datetime = implode(' ',$datetime);
    return date('Y-m-d H:i:s',strtotime($datetime));
}

// 删除文件夹及其下面的所有文件
function delFile($dir){
    $dh=opendir($dir);//打开文件夹
    while ($file=readdir($dh)) {
        if($file!="." && $file!="..") {
            $fullpath=$dir."/".$file;
            if(is_dir($fullpath)){
                delFile($fullpath);
            } else {
                unlink($fullpath);
            }
        }
    }
    closedir($dh);
    rmdir($dir);
}

//获取人性化价格
function getPrice($price){
    if($price > 100000000){
        return $price/100000000 . "亿";
    }elseif($price > 10000){
        return $price/10000 . "万";
    }elseif($price > 1000){
        return $price/1000 . "千";
    }else{
        return number_format($price,2,".","") . "元";
    }
}

// 查看数据大小
function getRealSize($size){
    $kb = 1024;          // Kilobyte
    $mb = 1024 * $kb;    // Megabyte
    $gb = 1024 * $mb;    // Gigabyte
    $tb = 1024 * $gb;    // Terabyte

    if($size < $kb)
        return $size.'B';

    else if($size < $mb)
        return round($size/$kb,2).'KB';

    else if($size < $gb)
        return round($size/$mb,2).'MB';

    else if($size < $tb)
        return round($size/$gb,2).'GB';

    else
        return round($size/$tb,2).'TB';
}

//获取文件夹大小
function getDirSize($dir){
    $handle = opendir($dir);
    $fsize  = '';

    while(($fname = readdir($handle)) !== false)
    {
        if($fname != '.' && $fname != '..')
        {
            if(is_dir("$dir/$fname"))
                $fsize += getDirSize("$dir/$fname");
            else
                $fsize += filesize("$dir/$fname");
        }
    }

    closedir($handle);
    if(empty($fsize)) $fsize = 0;

    return $fsize;
}

//获取IP
function getIP(){
    static $ip = NULL;
    if($ip !== NULL) return $ip;

    if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip  = trim($arr[0]);
    }
    else if(isset($_SERVER['HTTP_CLIENT_IP']))
    {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    else if(isset($_SERVER['REMOTE_ADDR']))
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    //IP地址合法验证
    $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
    return $ip;
}

// 检测是否移动端
function isMobile(){
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){
        return true;
    }
    return false;
}

相关文章

网友评论

      本文标题:常用PHP方法集合

      本文链接:https://www.haomeiwen.com/subject/mmbhlqtx.html