PHP常用函数收集

180it 2020-11-08 AM 1853℃ 0条
    /**
     * 过滤参数,防SQL注入
     * @param string $str 接受的参数
     * @return string
     */
    function filter_sql($str)
    {
        $farr = array(
            //"/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dump/is"
            "/select|insert|update|delete/is"
        );
        $str = preg_replace($farr, '', $str);
        return trim(addslashes($str));
    }
    



//消息框提示并跳转
function msg($a,$url){
  echo "<script>alert('".$a."');window.location.href='".$url."';</script>";
  exit();
}


//获取当前页面完整url
function GetPageUrl()
{
$nowurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
return $nowurl;
}

  /**
  * 取得当前页面完整url
  */
function geturl() {
    $url = '';
    if (isset($_SERVER['REQUEST_URI'])) {
      $url = $_SERVER['REQUEST_URI'];
    }
    else {
      $url = $_SERVER['Php_SELF'];
      $url .= empty($_SERVER['QUERY_STRING'])?'':'?'.$_SERVER['QUERY_STRING'];
    }
    return $url;
}
  

//随机字符 echo getrandstr();
    function getrandstr()
    {
        global $rands;
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randstr = str_shuffle($str); //打乱字符串
        $rands = substr($randstr, 0, 20); //substr(string,start,length);返回字符串的一部分
        return $rands;
    }
    
    
    /**
     * 获取客户端IP
     * @return string
     */
    function getip() { //获取客户端IP
        if ( isset($_SERVER[ "HTTP_CDN_SRC_IP" ]) ) { //获取网宿CDN真实客户IP
            return replace_ip( $_SERVER[ "HTTP_CDN_SRC_IP" ] );
        }
        if ( isset($_SERVER[ "HTTP_X_FORWARDED_FOR" ]) ) { //获取网宿、阿里云真实客户IP,参考:https://help.aliyun.com/knowledge_detail/40535.html
            return replace_ip( $_SERVER[ "HTTP_X_FORWARDED_FOR" ] );
        }
        if ( isset($_SERVER[ "HTTP_CLIENT_IP" ]) ) {
            return $_SERVER[ "HTTP_CLIENT_IP" ];
        }
        if ( isset($_SERVER[ "HTTP_X_FORWARDED" ]) ) {
            return $_SERVER[ "HTTP_X_FORWARDED" ];
        }
        if ( isset($_SERVER[ "HTTP_FORWARDED_FOR" ]) ) {
            return $_SERVER[ "HTTP_FORWARDED_FOR" ];
        }
        if ( isset($_SERVER[ "HTTP_FORWARDED" ]) ) {
            return $_SERVER[ "HTTP_FORWARDED" ];
        }
        $httpip = $_SERVER[ 'REMOTE_ADDR' ];
        if ( !preg_match( "/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/", $httpip ) ) {
            $httpip = "127.0.0.1";
        }
        return $httpip;
    }
    
    /**
     * 拆分代理IP
     * @return string
     */
    function replace_ip($ip)
    {
    
        if (!$ip) {
            return "";
        }
    
        $httpip_array = explode(",", $ip);
    
        if ($httpip_array[0]) {
    
            return $httpip_array[0];
    
        } else {
    
            return $ip;
    
        }
    
    }

/**
 * 返回json格式的处理结果,主要用于ajax
 * @param string $code 状态码,1成功,0失败
 * @param string $msg 返回的信息
 * @return string
 */
function result_json($code, $msg)
{
    $str = array("code" => $code, "msg" => $msg);
    return json($str);
}


/**
 * 过滤HTML参数
 * @param string $str 接受的参数
 * @return string
 */
function filter_html($str)
{
    $farr = array(
        "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
        "/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU"
    );
    $str = preg_replace($farr, '', $str);
    return trim(htmlspecialchars($str));
}


/**
 * 对象转数组
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj)
{
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
    return $obj;
}



/**
 * 获取浏览器以及版本号
 * @return string
 */
function get_userbrowser()
{
    $agent = Request::header('USER-AGENT');
    $browser = '';
    $browser_ver = '';

    if (preg_match('/UBrowser/i', $agent, $regs) || preg_match('/UC/i', $agent, $regs)) {
        $browser = 'UC浏览器';
        $browser_ver = '';
    }elseif (preg_match('/QQBrowser/i', $agent, $regs)) {
        $browser = 'QQ浏览器';
        $browser_ver = '';
    }elseif(preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
        $browser = 'OmniWeb';
        $browser_ver = $regs[2];
    }elseif(preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Netscape';
        $browser_ver = $regs[2];
    }elseif(preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Safari';
        $browser_ver = $regs[1];
    }elseif(preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
        $browser = 'IE';
        $browser_ver = $regs[1];
    }elseif(preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
        $browser = 'Opera';
        $browser_ver = $regs[1];
    }elseif(preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
        $browser = '(IE ' . $browser_ver . ') NetCaptor';
        $browser_ver = $regs[1];
    }elseif(preg_match('/Maxthon/i', $agent, $regs)) {
        $browser = '(IE ' . $browser_ver . ') Maxthon';
        $browser_ver = '';
    }elseif(preg_match('/360SE/i', $agent, $regs)) {
        $browser = '(IE ' . $browser_ver . ') 360SE';
        $browser_ver = '';
    }elseif(preg_match('/SE 2.x/i', $agent, $regs)) {
        $browser = '(IE ' . $browser_ver . ') 搜狗';
        $browser_ver = '';
    }elseif(preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'FireFox';
        $browser_ver = $regs[1];
    }elseif(preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Lynx';
        $browser_ver = $regs[1];
    }elseif(preg_match('/Chrome\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Chrome';
        $browser_ver = $regs[1];

    }

    if ($browser != '') {
        return $browser . ' ' . $browser_ver;
    } else {
        return 'unknow browser';
    }
}


/**
 * 获取客户端操作系统
 * @return string
 */
function get_userOS()
{
    $agent = Request::header('USER-AGENT');
    $os = false;
    if (strpos($agent, 'Android') !== false) {//strpos()定位出第一次出现字符串的位置,这里定位为0
        preg_match("/(?<=Android )[\d\.]{1,}/", $agent, $version);
        $os = 'Android '.$version[0];
    } elseif (strpos($agent, 'iPhone') !== false) {
        preg_match("/(?<=CPU iPhone OS )[\d\_]{1,}/", $agent, $version);
        $os = 'iPhone '.str_replace('_', '.', $version[0]);
    } elseif (strpos($agent, 'iPad') !== false) {
        preg_match("/(?<=CPU OS )[\d\_]{1,}/", $agent, $version);
        $os = 'iPad '.str_replace('_', '.', $version[0]);
    } else if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
        $os = 'Windows 95';
    } else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
        $os = 'Windows ME';
    } else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
        $os = 'Windows 98';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
        $os = 'Windows Vista';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
        $os = 'Windows 7';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
        $os = 'Windows 8';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
        $os = 'Windows 10';#添加win10判断
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
        $os = 'Windows XP';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
        $os = 'Windows 2000';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
        $os = 'Windows NT';
    } else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
        $os = 'Windows 32';
    } else if (preg_match('/linux/i', $agent)) {
        $os = 'Linux';
    } else if (preg_match('/unix/i', $agent)) {
        $os = 'Unix';
    } else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'SunOS';
    } else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'IBM OS/2';
    } else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) {
        $os = 'Macintosh';
    } else if (preg_match('/PowerPC/i', $agent)) {
        $os = 'PowerPC';
    } else if (preg_match('/AIX/i', $agent)) {
        $os = 'AIX';
    } else if (preg_match('/HPUX/i', $agent)) {
        $os = 'HPUX';
    } else if (preg_match('/NetBSD/i', $agent)) {
        $os = 'NetBSD';
    } else if (preg_match('/BSD/i', $agent)) {
        $os = 'BSD';
    } else if (preg_match('/OSF1/i', $agent)) {
        $os = 'OSF1';
    } else if (preg_match('/IRIX/i', $agent)) {
        $os = 'IRIX';
    } else if (preg_match('/FreeBSD/i', $agent)) {
        $os = 'FreeBSD';
    } else if (preg_match('/teleport/i', $agent)) {
        $os = 'teleport';
    } else if (preg_match('/flashget/i', $agent)) {
        $os = 'flashget';
    } else if (preg_match('/webzip/i', $agent)) {
        $os = 'webzip';
    } else if (preg_match('/offline/i', $agent)) {
        $os = 'offline';
    } else {
        $os = 'Unknown';
    }
    return $os;
}

/**
 * 获取本周所有日期
 */
function get_week($time = '', $format='Y-m-d'){
    $time = $time != '' ? $time : time();
    //获取当前周几
    $week = date('w', $time);
    $date = [];
    for ($i=1; $i<=7; $i++){
        $date[$i] = date($format ,strtotime( '+' . $i-$week .' days', $time));
    }
    return $date;
}

/**
 * 获取最近$n天所有日期
 */
function get_dates($n=7,$time = '', $format='Y-m-d'){
    $time = $time != '' ? $time : time();
    //组合数据
    $date = [];
    for ($i=1; $i<=$n; $i++){
        $date[$i] = date($format ,strtotime( '+' . $i-$n .' days', $time));
    }
    return $date;
}

/**
 * 获取最近N个月起至时间
 */
function get_month($n=6){
    for($i=0;$i<$n;$i++){
        if($i==0){
            $date[$i]['month'] = date('Y-m',mktime(0,0,0,date('m'),1,date('Y')));
            $date[$i]['start_time'] = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),1,date('Y')));
            $date[$i]['end_time'] = date('Y-m-d H:i:s',time());
        }else{
            $date[$i]['month'] = date('Y-m',mktime(0,0,0,date('m')-$i,1,date('Y')));
            $date[$i]['start_time'] = date('Y-m-d H:i:s',mktime(0,0,0,date('m')-$i,1,date('Y')));
            $date[$i]['end_time'] = date('Y-m-d H:i:s',mktime(23,59,59,date('m')-$i,date('t',mktime(0,0,0,date('m')-$i,1,date('Y'))),date('Y')));
        }
    }
    return array_reverse($date);
}

//中文截取
function cnString($text, $length){
    if(strlen($text) <= $length){
        return $text;
    }
    $str = substr($text, 0, $length) . chr(0) ; 
    return $str;
}


//获取访问客户端类型
function is_mobile()
{
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $is_pc = (strpos($agent, 'windows nt')) ? true : false;
        $is_mac = (strpos($agent, 'mac os')) ? true : false;
        $is_iphone = (strpos($agent, 'iphone')) ? true : false;
        $is_android = (strpos($agent, 'android')) ? true : false;
        $is_ipad = (strpos($agent, 'ipad')) ? true : false;
        

        if($is_pc){
              return  'Windows PC';
        }
        
        if($is_mac){
              return  'MAC';
        }
        
        if($is_iphone){
              return  'iphone';
        }
        
        if($is_android){
              return  '安卓';
        }
        
        if($is_ipad){
              return  'ipad';
        }
}


function t($str){
    $str=str_replace("\t","_",$str);
    $str=str_replace(" ","_",$str);
    $str=str_replace("(","_",$str);
    $str=str_replace(")","_",$str);
    $str=str_replace("<","_",$str);
    $str=str_replace(">","_",$str);
    $str=str_replace("/*","",$str);
    $str=str_replace("*/","",$str);
    $str=str_replace("#","",$str);
    $str=str_replace("-- ","",$str);
    $str=str_replace("'","‘",$str);
    $str=str_replace("\"","“",$str);
    return $str;
}



//文件大小转换
function ShowSpaceInfo($filesize){
$size =$filesize;
$showsize = $size . " Byte";
if($size > 1024){
$size = ($size / 1024);
$showsize = round($size,2) . " KB";
}
if($size > 1024){
$size = ($size / 1024);
$showsize = round($size,2) . " MB";
}
if($size > 1024){
$size = ($size / 1024);
$showsize = round($size,2) . " GB";
}
$ShowSpaceInfo=$showsize;
return $ShowSpaceInfo;
}

//获取文件扩展名
function getFileExt($a){
    return substr(strrchr($a, '.'), 1);
}



//消息框提示并跳转
function msg($a,$url){
  echo "<script>alert('".$a."');window.location.href='".$url."';</script>";
  exit();
}


//获取当前页面完整url
function GetPageUrl()
{
$nowurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
return $nowurl;
}

  /**
  * 取得当前页面完整url
  */
function geturl() {
    $url = '';
    if (isset($_SERVER['REQUEST_URI'])) {
      $url = $_SERVER['REQUEST_URI'];
    }
    else {
      $url = $_SERVER['Php_SELF'];
      $url .= empty($_SERVER['QUERY_STRING'])?'':'?'.$_SERVER['QUERY_STRING'];
    }
    return $url;
}
  

//随机字符 echo getrandstr();
    function getrandstr()
    {
        global $rands;
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randstr = str_shuffle($str); //打乱字符串
        $rands = substr($randstr, 0, 20); //substr(string,start,length);返回字符串的一部分
        return $rands;
    }
    
    
//获取当前PHP页面文件名
function php_self(){

    $php_self=substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);

    return $php_self;

}


//判断mysql 是否支持
function mysqliinstalled (){
  if (function_exists ("mysqli_connect")){
   return true;
  } else {
   return false;
  }
 }
 
 
 
function cutstr_html1($string,$length=0,$ellipsis=''){    
$string=strip_tags($string);    
$string=preg_replace('/\n/is','',$string);    
$string=preg_replace('/ | /is','',$string);    
$string=preg_replace('/ /is','',$string);    
preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/",$string,$string);    
if(is_array($string)&&!empty($string[0])){    
if(is_numeric($length)&&$length){    
$string=join('',array_slice($string[0],0,$length)).$ellipsis;    
 }else{    
 $string=implode('',$string[0]);    
 }    
}else{    
 $string='';    
}    
return $string;    
}   
function cutstr_html($text, $length)
{
     if(mb_strlen($text, 'utf8') > $length) 
    return mb_substr($text, 0, $length, 'utf8').'...';
     return $text;
}


function clearHtml($content){    
$content=preg_replace("/<a[^>]*>/i","",$content);    
$content=preg_replace("/<\/a>/i","",$content);    
$content=preg_replace("/<div[^>]*>/i","",$content);    
$content=preg_replace("/<\/div>/i","",$content);    
$content=preg_replace("/<!--[^>]*-->/i","",$content);//注释内容        
$content=preg_replace("/style=.+?['|\"]/i",'',$content);//去除样式        
$content=preg_replace("/class=.+?['|\"]/i",'',$content);//去除样式        
$content=preg_replace("/id=.+?['|\"]/i",'',$content);//去除样式           
$content=preg_replace("/lang=.+?['|\"]/i",'',$content);//去除样式            
$content=preg_replace("/width=.+?['|\"]/i",'',$content);//去除样式         
$content=preg_replace("/height=.+?['|\"]/i",'',$content);//去除样式         
$content=preg_replace("/border=.+?['|\"]/i",'',$content);//去除样式         
$content=preg_replace("/face=.+?['|\"]/i",'',$content);//去除样式         
$content=preg_replace("/face=.+?['|\"]/",'',$content);//去除样式 只允许小写 正则匹配没有带 i 参数      
return $content;    
}

function formatdata($addtime){

    $rsdatay=date("Y",strtotime($addtime));
    $rsdatam=date("m",strtotime($addtime)); 
    $rsdatad=date("d",strtotime($addtime));
    return $rsdatay."-".$rsdatam."-".$rsdatad;
}include_once "key.php"; 
function formatdata_d($addtime){

    $rsdatam=date("m",strtotime($addtime)); 
    $rsdatad=date("d",strtotime($addtime));
    return $rsdatam."-".$rsdatad;
}



//防注入函数 主要是为了防止恶意写入后台数据库
function input_check($sql_str) { 
   $check=eregi('select|order by|from|and|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|system_user|user|current_user|database|version', $sql_str);     // 进行过滤 
   if($check){ 
       echo "非法注入内容!"; 
       exit(); 
   }else{ 
       return $sql_str; 
   } 

} 


function injCheck($sql_str) { 
    $check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);
    if ($check) {
        ok_info('/index.html','非法字符');
        exit;
    } else {
        return $sql_str;
    }
}




/**操作成功提示**/
function ok_info($url,$langinfo){
    if($url==0){
        echo("<script type='text/javascript'> alert('$langinfo');history.go(-1);</script>");        
    }else{
        echo("<script type='text/javascript'> alert('$langinfo');location.href= '$url'; </script>");  
    }
    exit;
}

function getIP() {
    $realip = ''; //设置默认值
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $realip = $_SERVER['HTTP_CLIENT_IP'];
    } else {
        $realip = $_SERVER['REMOTE_ADDR'];
    }

    preg_match('/^((?:\d{1,3}\.){3}\d{1,3})/',$realip,$match);
    return $match?$match[0]:false;
}





//文件大小转换
function ShowSpaceInfo($filesize){
$size =$filesize;
$showsize = $size . " Byte";
if($size > 1024){
$size = ($size / 1024);
$showsize = round($size,2) . " KB";
}
if($size > 1024){
$size = ($size / 1024);
$showsize = round($size,2) . " MB";
}
if($size > 1024){
$size = ($size / 1024);
$showsize = round($size,2) . " GB";
}
$ShowSpaceInfo=$showsize;
return $ShowSpaceInfo;
}

//获取文件扩展名
function getFileExt($a){
    return substr(strrchr($a, '.'), 1);
}



function deldir($dir) { 
  //先删除目录下的文件: 
  $dh=opendir($dir); 
  while ($file=readdir($dh)) { 
    if($file!="." && $file!="..") { 
      $fullpath=$dir."/".$file; 
      if(!is_dir($fullpath)) { 
          unlink($fullpath); 
      } else { 
          deldir($fullpath); 
      } 
    } 
  } 
  closedir($dh); 
  //删除当前文件夹: 
  if(rmdir($dir)) { 
    return true; 
  } else { 
    return false; 
  } 
}

function safe($val)
    {
        $val =trim($val);
        if (!get_magic_quotes_gpc()) // 判断magic_quotes_gpc是否为打开
        {
            $val = addslashes($val); // magic_quotes_gpc没有打开的时候把数据过滤
        }
    
        if ($val === '') {
            return '';
        }
        if (is_int($val)) {
            return intval($val);
        }
        if (is_float($val)) {
            if (preg_match('/^[+-]?(\\d*\\.\\d+([eE]?[+-]?\\d+)?|\\d+[eE][+-]?\\d+)$/', $val)) {
                return $val;
            }
            return false;
        }
        if (is_string($val)) {
            if (preg_match('/<script>(.*)<\\/script>/iS', $val, $match)) {
                $val = $match[1];
            }
            if (preg_match('/<iframe>(.*)<\\/iframe>/iS', $val, $match)) {
                $val = $match[1];
            }
            return $val;
        }
        return $val;
    }
    
    function usersafe($str)
    {
        if (empty($str)) return false;
        $str = str_replace( '<br>', "", $str);
        $str = str_replace( '<br/>', "", $str);
        $str = str_replace( '<p>', "", $str);
        $str = str_replace( '</p>', "", $str);
        $str = str_replace( 'CR', "", $str);
        $str = str_replace( 'ASCII', "", $str);
        $str = str_replace( 'ASCII 0x0d', "", $str);
        $str = str_replace( 'LF', "", $str);
        $str = str_replace( 'ASCII 0x0a', "", $str);
        $str = str_replace( '%', "", $str);
        $str = str_replace( 'eval', "", $str);
        $str = str_replace( 'open', "", $str);
        $str = str_replace( 'sysopen', "", $str);
        $str = str_replace( 'system', "", $str);
        $str = str_replace( '$', "", $str);
        $str = str_replace( 'ASCII 0x08', "", $str);
        $str = str_replace("<SCRIPT>", "", $str);
        $str = str_replace("</SCRIPT>", "", $str);
        $str = str_replace("<script>", "", $str);
        $str = str_replace("</script>", "", $str);
        $str = str_replace("select","",$str);
        $str = str_replace("join","",$str);
        $str = str_replace("union","",$str);
        $str = str_replace("where","",$str);
        $str = str_replace("insert","",$str);
        $str = str_replace("delete","",$str);
        $str = str_replace("update","",$str);
        $str = str_replace("like","",$str);
        $str = str_replace("drop","",$str);
        $str = str_replace("DROP","",$str);
        $str = str_replace("create","",$str);
        $str = str_replace("modify","",$str);
        $str = str_replace("rename","",$str);
        $str = str_replace("alter","",$str);
        $str = str_replace("cas","",$str);
        $str = str_replace("css","'",$str);
        $str = str_replace("CSS","'",$str);
        $str = str_replace("<!--","",$str);
        $str = str_replace("convert","",$str);
        $str = str_replace("md5","",$str);
        $str = str_replace("passwd","",$str);
        $str = str_replace("password","",$str);
        $str = str_replace("../","",$str);
        $str = str_replace("./","",$str);
        $str = str_replace("Array","",$str);
        $str = str_replace("or 1='1'","",$str);
        $str = str_replace(";set|set&set;","",$str);
        $str = str_replace("`set|set&set`","",$str);
        $str = str_replace("--","",$str);
        $str = str_replace("OR","",$str);
        $str = str_replace("*","",$str);
        $str = str_replace("-","",$str);
        $str = str_replace("+","",$str);
        $str = str_replace("'/","",$str);
        $str = str_replace("-- ","",$str);
        $str = str_replace(" -- ","",$str);
        $str = str_replace(" --","",$str);
        $str = str_replace("(","",$str);
        $str = str_replace(")","",$str);
        $str = str_replace("{","",$str);
        $str = str_replace("}","",$str);
        $str = str_replace("-1","",$str);
        $str = str_replace("response","",$str);
        $str = str_replace("write","",$str);
        $str = str_replace("|","",$str);
        $str = str_replace("`","",$str);
        $str = str_replace("etc","",$str);
        $str = str_replace("root","",$str);
        $str = str_replace("!=","",$str);
        $str = str_replace("$","",$str);
        $str = str_replace("&","",$str);
        $str = str_replace("&&","",$str);
        $str = str_replace("==","",$str);
        $str = str_replace("mailto:","",$str);
        $str = str_replace("CHAR","",$str);
        $str = str_replace("char","",$str);
        $str=preg_replace("/<\!--.*?-->/si","",$str); //注释
        $str=preg_replace("/<(\!.*?)>/si","",$str); //过滤DOCTYPE
        $str=preg_replace("/<(\/?html.*?)>/si","",$str); //过滤html标签
        $str=preg_replace("/<(\/?head.*?)>/si","",$str); //过滤head标签
        $str=preg_replace("/<(\/?meta.*?)>/si","",$str); //过滤meta标签
        $str=preg_replace("/<(\/?body.*?)>/si","",$str); //过滤body标签
        $str=preg_replace("/<(\/?link.*?)>/si","",$str); //过滤link标签
        $str=preg_replace("/<(\/?form.*?)>/si","",$str); //过滤form标签
        $str=preg_replace("/cookie/si","COOKIE",$str); //过滤COOKIE标签
        
        $str=preg_replace("/<(applet.*?)>(.*?)<(\/applet.*?)>/si","",$str); //过滤applet标签
        $str=preg_replace("/<(\/?applet.*?)>/si","",$str); //过滤applet标签
        
        $str=preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si","",$str); //过滤style标签
        $str=preg_replace("/<(\/?style.*?)>/si","",$str); //过滤style标签
        
        $str=preg_replace("/<(title.*?)>(.*?)<(\/title.*?)>/si","",$str); //过滤title标签
        $str=preg_replace("/<(\/?title.*?)>/si","",$str); //过滤title标签
        
        $str=preg_replace("/<(object.*?)>(.*?)<(\/object.*?)>/si","",$str); //过滤object标签
        $str=preg_replace("/<(\/?objec.*?)>/si","",$str); //过滤object标签
        
        $str=preg_replace("/<(noframes.*?)>(.*?)<(\/noframes.*?)>/si","",$str); //过滤noframes标签
        $str=preg_replace("/<(\/?noframes.*?)>/si","",$str); //过滤noframes标签
        
        $str=preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","",$str); //过滤frame标签
        $str=preg_replace("/<(\/?i?frame.*?)>/si","",$str); //过滤frame标签
        
        $str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","",$str); //过滤script标签
        $str=preg_replace("/<(\/?script.*?)>/si","",$str); //过滤script标签
        $str=preg_replace("/javascript/si","Javascript",$str); //过滤script标签
        $str=preg_replace("/vbscript/si","Vbscript",$str); //过滤script标签
        $str=preg_replace("/on([a-z]+)\s*=/si","On\\1=",$str); //过滤script标签
        $str=preg_replace("/&#/si","&#",$str); //过滤script标签
        return $str;
    }
    
    function zhongwen($str){
       //转换 GB2312 -> UTF-8
        //$str = mb_convert_encoding($str, 'UTF-8', 'GB2312');
        
        preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
        $str = join('', $matches[0]);

            //转换 UTF-8 -> GB2312
        //$str = mb_convert_encoding($str, 'GB2312', 'UTF-8');
        
        echo $str; //输出 中文字符
    }
    
    //验证是否为指定长度的字母/数字组合
    function fun_text1($num1,$num2,$str)
    {
        Return (preg_match("/^[a-zA-Z0-9]{".$num1.",".$num2."}$/",$str))?true:false;
    }

//验证是否为指定长度数字
    function fun_text2($num1,$num2,$str)
    {
        return (preg_match("/^[0-9]{".$num1.",".$num2."}$/i",$str))?true:false;
    }
//验证是否为指定长度汉字
    function fun_font($num1,$num2,$str)
    {
// preg_match("/^[\xa0-\xff]{1,4}$/", $string);
        
        return (preg_match("/^([\x81-\xfe][\x40-\xfe]){".$num1.",".$num2."}$/",$str))?true:false;
    }
//验证身份证号码
    function fun_status($str)
    {
        return (preg_match('/(^([\d]{15}|[\d]{18}|[\d]{17}x)$)/',$str))?true:false;
    }
//验证邮件地址
    function fun_email($str){
        return (preg_match('/^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$/',$str))?true:false;
    }
//验证电话号码
    function fun_phone($str)
    {
        return (preg_match("/^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/",$str))?true:false;
    }
//验证邮编
    function fun_zip($str)
    {
        return (preg_match("/^[1-9]\d{5}$/",$str))?true:false;
    }
//验证url地址
    function fun_url($str)
    {
        return (preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/",$str))?true:false;
    }
// 数据入库 转义 特殊字符 传入值可为字符串 或 一维数组
    function data_join(&$data)
    {
        if(get_magic_quotes_gpc() == false)
        {
            if (is_array($data))
            {
                foreach ($data as $k => $v)
                {
                    $data[$k] = addslashes($v);
                }
            }
            else
            {
                $data = addslashes($data);
            }
        }
        Return $data;
    }
// 数据出库 还原 特殊字符 传入值可为字符串 或 一/二维数组
    function data_revert(&$data)
    {
        if (is_array($data))
        {
            foreach ($data as $k1 => $v1)
            {
                if (is_array($v1))
                {
                    foreach ($v1 as $k2 => $v2)
                    {
                        $data[$k1][$k2] = stripslashes($v2);
                    }
                }
                else
                {
                    $data[$k1] = stripslashes($v1);
                }
            }
        }
        else
        {
            $data = stripslashes($data);
        }
        Return $data;
    }
// 数据显示 还原 数据格式 主要用于内容输出 传入值可为字符串 或 一/二维数组
// 执行此方法前应先data_revert(),表单内容无须此还原
    function data_show(&$data)
    {
        if (is_array($data))
        {
            foreach ($data as $k1 => $v1)
            {
                if (is_array($v1))
                {
                    foreach ($v1 as $k2 => $v2)
                    {
                        $data[$k1][$k2]=nl2br(htmlspecialchars($data[$k1][$k2]));
                        $data[$k1][$k2]=str_replace(" "," ",$data[$k1][$k2]);
                        $data[$k1][$k2]=str_replace("\n","<br>\n",$data[$k1][$k2]);
                    }
                }
                else
                {
                    $data[$k1]=nl2br(htmlspecialchars($data[$k1]));
                    $data[$k1]=str_replace(" "," ",$data[$k1]);
                    $data[$k1]=str_replace("\n","<br>\n",$data[$k1]);
                }
            }
        }
        else
        {
            $data=nl2br(htmlspecialchars($data));
            $data=str_replace(" "," ",$data);
            $data=str_replace("\n","<br>\n",$data);
        }
        Return $data;
    }
    /*
 //要求输入内容由数字、字母、下划线组成,不能以数字开头,有位数限制
 //参数:$str,$num1,$num2
 //返回值: 匹配成功返回匹配的次数
 */
     function checkStr($str,$num1,$num2){
    //正则
    $reg='/^[a-zA-Z_]\w{'.($num1-1).','.($num2-1).'}$/';
    return preg_match($reg,$str);
}


/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf-8
开始长度默认为 0
*/
    
    function subString($string, $sublen, $start = 0, $code = 'UTF-8')
    {
        if($code == 'UTF-8')
        {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);
            
            if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
            return join('', array_slice($t_string[0], $start, $sublen));
        }
        else
        {
            $start = $start*2;
            $sublen = $sublen*2;
            $strlen = strlen($string);
            $tmpstr = '';
            
            for($i=0; $i< $strlen; $i++)
            {
                if($i>=$start && $i< ($start+$sublen))
                {
                    if(ord(substr($string, $i, 1))>129)
                    {
                        $tmpstr.= substr($string, $i, 2);
                    }
                    else
                    {
                        $tmpstr.= substr($string, $i, 1);
                    }
                }
                if(ord(substr($string, $i, 1))>129) $i++;
            }
            if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
            return $tmpstr;
        }
    }
    
    
    
    
//只取汉字
    function match_chinese($chars, $encoding = 'utf8')
    {
        $pattern = ($encoding == 'utf8') ? '/[\x{4e00}-\x{9fa5}]/u' : '/[\x80-\xFF]/';
        preg_match_all($pattern, $chars, $result);
        $temp = join('', $result[0]);
        return $temp;
    }
    
    
    function isUrl($s)
    {
        return preg_match('/^http[s]?:\/\/' .
                '(([0-9]{1,3}\.){3}[0-9]{1,3}' . // IP形式的URL- 199.194.52.184
                '|' . // 允许IP和DOMAIN(域名)
                '([0-9a-z_!~*\'()-]+\.)*' . // 三级域验证- www.
                '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.' . // 二级域验证
                '[a-z]{2,6})' .  // 顶级域验证.com or .museum
                '(:[0-9]{1,4})?' .  // 端口- :80
                '((\/\?)|' .  // 如果含有文件对文件部分进行校验
                '(\/[0-9a-zA-Z_!~\*\'\(\)\.;\?:@&=\+\$,%#-\/]*)?)$/',
                $s) == 1;
    }
    
    function getOrderID()
    {
        // return date('Y') . date('m') . date('d') . date('H') . date('i') . date('s') . mt_rand(10000, 99999);
        return date('Y') . date('m') . date('d') . date('H') . date('i') . date('s') . mt_rand(100, 999);
    }


/**
* POST方式访问接口
* @param string $data
* @return mixed
*/
    function httpClient($Url,$data) {
        $data = http_build_query($data);
        
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $Url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $res = curl_exec($ch);
            curl_close($ch);
            return $res;
        } catch (Exception $e) {
            $errorMsg = $e->getMessage();
            return false;
        }
    }
    
    
    
    function tojson($zt, $msg, $url)
    {
        
        exit(json_encode(["zt" => $zt, "msg" => $msg, "url" => $url]));
    }
    
    
    
    
//监测手机电脑客户端
function isMobile(){    
    $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';    
    $useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';      
    function CheckSubstrs($substrs,$text){    
        foreach($substrs as $substr)    
            if(false!==strpos($text,$substr)){    
                return true;    
            }    
            return false;    
    }  

    $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');  

    $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');    
    $found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) ||    
      CheckSubstrs($mobile_token_list,$useragent);    
    if ($found_mobile){    
        return true;    
    }else{    
        return false;    
    }    
}  



/* 方法一:获取随机字符串
     * @param number $length 长度
     * @param string $type 类型
     * @param number $convert 转换大小写
     * @return string 随机字符串
     */
    function random($length = 6, $type = 'string', $convert = 0)
    {
        $config = array(
            'number' => '1234567890',
            'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );
 
        if (!isset($config[$type]))
            $type = 'string';
        $string = $config[$type];
 
        $code = '';
        $strlen = strlen($string) - 1;
        for ($i = 0; $i < $length; $i++) {
            $code .= $string{mt_rand(0, $strlen)};
        }
        if (!empty($convert)) {
            $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
        }
        return $code;
    }

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP常用函数收集