欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php 的常用函数FUNCTION

程序员文章站 2024-01-16 17:48:52
...
php
/**
 * 获取客户端IP
 * @return [string] [description]
 */
functiongetClientIp(){
    $ip= NULL;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]);}elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
        $ip=$_SERVER['HTTP_CLIENT_IP'];}elseif(isset($_SERVER['REMOTE_ADDR'])){
        $ip=$_SERVER['REMOTE_ADDR'];}// IP地址合法验证
    $ip=(false!==ip2long($ip))?$ip:'0.0.0.0';return$ip;}/**
 * 获取在线IP
 * @return String
 */
functiongetOnlineIp($format=0){global$S_GLOBAL;if(empty($S_GLOBAL['onlineip'])){if(getenv('HTTP_CLIENT_IP')&&strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')){
            $onlineip=getenv('HTTP_CLIENT_IP');}elseif(getenv('HTTP_X_FORWARDED_FOR')&&strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')){
            $onlineip=getenv('HTTP_X_FORWARDED_FOR');}elseif(getenv('REMOTE_ADDR')&&strcasecmp(getenv('REMOTE_ADDR'),'unknown')){
            $onlineip=getenv('REMOTE_ADDR');}elseif(isset($_SERVER['REMOTE_ADDR'])&&$_SERVER['REMOTE_ADDR']&&strcasecmp($_SERVER['REMOTE_ADDR'],'unknown')){
            $onlineip=$_SERVER['REMOTE_ADDR'];}
        preg_match("/[\d\.]{7,15}/",$onlineip,$onlineipmatches);
        $S_GLOBAL['onlineip']=$onlineipmatches[0]?$onlineipmatches[0]:'unknown';}if($format){
        $ips=explode('.',$S_GLOBAL['onlineip']);for($i=0;$i3;$i++){
            $ips[$i]=intval($ips[$i]);}
        returnsprintf('%03d%03d%03d',$ips[0],$ips[1],$ips[2]);}else{return$S_GLOBAL['onlineip'];}}/**
 * 获取url
 * @return [type] [description]
 */
functiongetUrl(){
  $pageURL='http';if(isset($_SERVER["HTTPS"])&&$_SERVER["HTTPS"]=="on"){
    $pageURL.="s";}
  $pageURL.="://";if($_SERVER["SERVER_PORT"]!="80"){
    $pageURL.=$_SERVER["HTTP_HOST"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];}else{
    $pageURL.=$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];}return$pageURL;}/**
 * 获取当前站点的访问路径根目录
 * @return [type] [description]
 */
functiongetSiteUrl(){
    $uri=$_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);return'http://'.$_SERVER['HTTP_HOST'].substr($uri,0,strrpos($uri,'/')+1);}/**
 * 字符串截取,支持中文和其他编码
 * @param  [string]  $str     [字符串]
 * @param  integer $start   [起始位置]
 * @param  integer $length  [截取长度]
 * @param  string  $charset [字符串编码]
 * @param  boolean $suffix  [是否有省略号]
 * @return [type]           [description]
 */
functionmsubstr($str,$start=0,$length=15,$charset="utf-8",$suffix=true){if(function_exists("mb_substr")){
        returnmb_substr($str,$start,$length,$charset);}elseif(function_exists('iconv_substr')){
        returniconv_substr($str,$start,$length,$charset);}
    $re['utf-8']="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312']="/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']="/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']="/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset],$str,$match);
    $slice= join("",array_slice($match[0],$start,$length));if($suffix){return$slice."…";}return$slice;}/**
 * php 实现js escape 函数
 * @param  [type] $string   [description]
 * @param  string $encoding [description]
 * @return [type]           [description]
 */
functionescape($string,$encoding='UTF-8'){
  $return=null;for($x=0;$x mb_strlen($string,$encoding);$x++){
    $str= mb_substr($string,$x,1,$encoding);if(strlen($str)>1){// 多字节字符
      $return.="%u".strtoupper(bin2hex(mb_convert_encoding($str,'UCS-2',$encoding)));}else{
      $return.="%".strtoupper(bin2hex($str));}}return$return;}/**
 * php 实现 js unescape函数
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
functionunescape($str){
    $str= rawurldecode($str);
    preg_match_all("/(?:%u.{4})|.{4};|\d+;|.+/U",$str,$r);
    $ar=$r[0];foreach($aras$k=>$v){if(substr($v,0,2)=="%u"){
            $ar[$k]= iconv("UCS-2","utf-8//IGNORE",pack("H4",substr($v,-4)));}elseif(substr($v,0,3)==""){
            $ar[$k]= iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1)));}elseif(substr($v,0,2)==""){
            echosubstr($v,2,-1)."";
            $ar[$k]= iconv("UCS-2","utf-8",pack("n",substr($v,2,-1)));}}
    returnjoin("",$ar);}/**
 * 数字转人名币
 * @param  [type] $num [description]
 * @return [type]      [description]
 */
functionnum2rmb ($num){
    $c1="零壹贰叁肆伍陆柒捌玖";
    $c2="分角元拾佰仟万拾佰仟亿";
    $num=round($num,2);
    $num=$num*100;if(strlen($num)>10){return"oh,sorry,the number is too long!";}
    $i=0;
    $c="";while(1){if($i==0){
            $n=substr($num,strlen($num)-1,1);}else{
            $n=$num%10;}
        $p1=substr($c1,3*$n,3);
        $p2=substr($c2,3*$i,3);if($n!='0'||($n=='0'&&($p2=='亿'||$p2=='万'||$p2=='元'))){
            $c=$p1.$p2.$c;}else{
            $c=$p1.$c;}
        $i=$i+1;
        $num=$num/10;
        $num=(int)$num;if($num==0){break;}}
    $j=0;
    $slen=strlen($c);while($j$slen){
        $m=substr($c,$j,6);if($m=='零元'||$m=='零万'||$m=='零亿'||$m=='零零'){
            $left=substr($c,0,$j);
            $right=substr($c,$j+3);
            $c=$left.$right;
            $j=$j-3;
            $slen=$slen-3;}
        $j=$j+3;}if(substr($c,strlen($c)-3,3)=='零'){
        $c=substr($c,0,strlen($c)-3);}// if there is a '0' on the end , chop it outreturn$c."整";}/**
 * 特殊的字符
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
functionmakeSemiangle($str){
  $arr=array('0'=>'0','1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5','6'=>'6','7'=>'7','8'=>'8','9'=>'9','A'=>'A','B'=>'B','C'=>'C','D'=>'D','E'=>'E','F'=>'F','G'=>'G','H'=>'H','I'=>'I','J'=>'J','K'=>'K','L'=>'L','M'=>'M','N'=>'N','O'=>'O','P'=>'P','Q'=>'Q','R'=>'R','S'=>'S','T'=>'T','U'=>'U','V'=>'V','W'=>'W','X'=>'X','Y'=>'Y','Z'=>'Z','a'=>'a','b'=>'b','c'=>'c','d'=>'d','e'=>'e','f'=>'f','g'=>'g','h'=>'h','i'=>'i','j'=>'j','k'=>'k','l'=>'l','m'=>'m','n'=>'n','o'=>'o','p'=>'p','q'=>'q','r'=>'r','s'=>'s','t'=>'t','u'=>'u','v'=>'v','w'=>'w','x'=>'x','y'=>'y','z'=>'z','('=>'(',')'=>')','〔'=>'[','〕'=>']','【'=>'[','】'=>']','〖'=>'[','〗'=>']','{'=>'{','}'=>'}','《'=>','》'=>'>','%'=>'%','+'=>'+','—'=>'-','-'=>'-','~'=>'-',':'=>':','。'=>'.','、'=>',',','=>'.','、'=>'.',';'=>';','?'=>'?','!'=>'!','…'=>'-','‖'=>'|','”'=>'"','“'=>'"','’'=>'`','‘'=>'`','|'=>'|','〃'=>'"',' '=>' ','.'=>'.');
  returnstrtr($str,$arr);}/**
 * 下载
 * @param  [type] $filename [description]
 * @param  string $dir      [description]
 * @return [type]           [description]
 */
functiondownloads($filename,$dir='./'){
    $filepath=$dir.$filename;if(!file_exists($filepath)){
        header("Content-type: text/html; charset=utf-8");
        echo"File not found!";exit;}else{
        $file=fopen($filepath,"r");Header("Content-type: application/octet-stream");Header("Accept-Ranges: bytes");Header("Accept-Length: ".filesize($filepath));Header("Content-Disposition: attachment; filename=".$filename);
        echofread($file,filesize($filepath));
        fclose($file);}}/**
 * 创建一个目录树
 * @param  [type]  $dir  [description]
 * @param  integer $mode [description]
 * @return [type]        [description]
 */
functionmkdirs($dir,$mode=0777){if(!is_dir($dir)){
        mkdirs(dirname($dir),$mode);
        returnmkdir($dir,$mode);}
    returntrue;}3.[代码]curl 
functionxcurl($url,$ref=null,$post=array(),$ua="Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre",$print=false){
    $ch= curl_init();
    curl_setopt($ch, CURLOPT_AUTOREFERER,true);if(!empty($ref)){
        curl_setopt($ch, CURLOPT_REFERER,$ref);}
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);if(!empty($ua)){
        curl_setopt($ch, CURLOPT_USERAGENT,$ua);}if(count($post)>0){
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post);}
    $output= curl_exec($ch);
    curl_close($ch);if($print){print($output);}else{return$output;}}4.[代码]日期时间函数/**
 * 根据一个时间戳得到详细信息
 * @param  [type] $time [时间戳]
 * @return [type]      
 * @author [yangsheng@yahoo.com]
 */
functiongetDateInfo($time){
    $day_of_week_cn=array("日","一","二","三","四","五","六");//中文星期
    $week_of_month_cn=array('','第1周','第2周','第3周','第4周','第5周','第6周');#本月第几周
    $tenDays= getTenDays(date('j',$time));#获得旬
    $quarter= getQuarter(date('n',$time),date('Y',$time));#获取季度    $dimDate=array('date_key'=>strtotime(date('Y-m-d',$time)),#日期时间戳'date_day'=>date('Y-m-d',$time),#日期YYYY-MM-DD'current_year'=>date('Y',$time),#数字年'current_quarter'=>$quarter['current_quarter'],#季度'quarter_cn'=>$quarter['quarter_cn'],'current_month'=>date('n',$time),#月'month_cn'=>date('Y-m',$time),#月份'tenday_of_month'=>$tenDays['tenday_of_month'],#数字旬'tenday_cn'=>$tenDays['tenday_cn'],#中文旬'week_of_month'=>ceil(date('j',$time)/7),#本月第几周'week_of_month_cn'=>$week_of_month_cn[ceil(date('j',$time)/7)],#中文当月第几周'day_of_year'=>date('z',$time)+1,#年份中的第几天'day_of_month'=>date('j',$time),#得到几号'day_of_week'=>date('w',$time)>0?date('w',$time):7,#星期几'day_of_week_cn'=>'星期'.$day_of_week_cn[date('w',$time)],);return$dimDate;}/**
 * 获得日期是上中下旬
 * @param  [int] $j [几号]
 * @return [array]    [description]
 * @author [yangsheng@yahoo.com]
 */
functiongetTenDays($j){    $j=intval($j);if($j1||$j>31){
        returnfalse;#不是日期}
   $tenDays=ceil($j/10);switch($tenDays){
        case1:#上旬
            returnarray('tenday_of_month'=>1,'tenday_cn'=>'上旬',);break;
        case2:#中旬
             returnarray('tenday_of_month'=>2,'tenday_cn'=>'中旬',);break;default:#下旬
            returnarray('tenday_of_month'=>3,'tenday_cn'=>'下旬',);break;}
    returnfalse;}/**
 * 根据月份获得当前第几季度
 * @param  [int] $n [月份]
 * @param  [int] $y [年]
 * @return [array]    [description]
 */
functiongetQuarter($n,$y=null){
     $n=intval($n);if($n1||$n>12){
        returnfalse;#不是月份}
    $quarter=ceil($n/3);switch($quarter){
        case1:#第一季度
            returnarray('current_quarter'=>1,'quarter_cn'=>$y?$y.'-Q1':'Q1');break;
        case2:#第二季度
            returnarray('current_quarter'=>2,'quarter_cn'=>$y?$y.'-Q2':'Q2');break;
         case3:#第三季度
            returnarray('current_quarter'=>3,'quarter_cn'=>$y?$y.'-Q3':'Q3');break;
         case4:#第四季度
            returnarray('current_quarter'=>4,'quarter_cn'=>$y?$y.'-Q4':'Q4');break;}
     returnfalse;}
网站地址:http://www.5k5c.com/blog/175

以上就介绍了 php 的常用函数FUNCTION,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。