Custom functions commonly used in PHP

Time:2020-2-13

Catalog

  • PHP common custom function class Download
  • PHP sets character encoding to UTF-8
  • Conversion between GB2312 and UTF8
  • Path format (replace double slash with single slash)
  • Get the directory of the current file
  • Printout
  • API return information
  • String truncation
    • Method 1:
    • Method two:
  • String make by ID to makeById
  • String conversion in JSON format of array string object
  • Cast
  • PHP serialize and return serialize unserialize
  • Create log file
  • Returns the data of one segment of a 2D array
  • Get IP address
  • PHP restrict IP access only allow specified IP access allow * wildcard to filter IP
  • Get the part of the address path from 0 to the first \ line
  • Get the file path where the current file is located
  • Get random string
  • Chinese string inversion
  • Check whether the destination folder exists, and if not, create the directory automatically
  • Get file modification time by default
  • Determine suffix type
  • Check file type
  • Gets the file suffix and determines whether it is in the defined array
  • Determine whether the path is a file or a directory
  • Calculate file or directory byte size
  • Receive asynchronous get messages
  • Get request of curl
  • Post request of curl
  • Post & get request of curl
  • Judge whether the array type parameter contains empty element value
  • Determine whether necessary parameters are passed in

PHP common custom function class Download

https://pan.baidu.com/s/18ZuQm5cx3ynQtQqcQgK0Vw


PHP sets character encoding to UTF-8

header("Content-Type: text/html;charset=utf-8");


Conversion between GB2312 and UTF8

Echo iconv ('gb2312 ',' UTF-8 // ignore ', $STR); // change the string encoding from GB2312 to UTF-8
//Ignore means to ignore errors during conversion. Without ignore parameter, all strings following the character cannot be saved.
iconv("UTF-8","GB2312//IGNORE",$data);    
Print_r (iconv_get_encoding()); // get the current page encoding information
// transcoding
function gbk($str){return iconv('utf-8','gbk',$str);}
function utf8($str){return iconv('gbk','utf-8',$str);}

Path format (replace double slash with single slash)

function path_formate($str){
    return str_replace('\\','\',$str);
}

Get the directory of the current file

Method 1:
define('BASE_PATH',rtrim(str_replace('\','/',__DIR__).'/'));
Method two:
define('BASE_DIR', rtrim(str_replace('\', '/', dirname(__FILE__)),'/').'/');

Printout

function dump($var)
{
    echo '';
    print_r($var);
    echo '';
}

function vp($var)
{
    echo '';
    var_dump($var);
    echo '';
}

function dd($var)
{
    echo '';
    var_dump($var);
    echo '';
    die;
}

API return information

/**
*Data return
 *@ param [int] $code [result code 200: normal / 4 * * data problem / 5 * * server problem]
 *@ param [string] $MSG [returned prompt]
 *@ param [array] $data [returned data]
 *@ return [string] [final JSON data]
*/
public function return_msg($code, $msg = '', $data = []) {
 
    /***********Combined data***********/
    $return_data['code'] = $code;
    $return_data['msg']  = $msg;
    $return_data['data'] = $data;
 
    /***********Return information and terminate script***********/
    echo json_encode($return_data,JSON_UNESCAPED_UNICODE);
    die;
}

String truncation

Method 1:

In common.php

//String truncation and display ellipsis exceeded
function subtext($text, $length)
{
if(mb_strlen($text, ‘utf8’) > $length)
return mb_substr($text,0,$length,’utf8′).’ …’;
return $text;
}

In template,
{$tops.title | subtext=18}

Method two:

In common.php

//String truncation

function cut_str($sourcestr,$cutlength)  

{  

   $returnstr='';  

   $i=0;  

   $n=0;  

   $str_length = strlen ($sourcestr); // the number of bytes in the string  

   while (($nand ($i<=$str_length))  

   {  

      $temp_str=substr($sourcestr,$i,1);  

      $ascnum = ord ($temp_str); // get the ASCII code of the $I character in the string  

      If ($ascnum > = 224) // if the ASCII bit height is 224,  

      {  

$returnStr = $returnstr.substr ($sourcestr, $I, 3); // count 3 consecutive characters as a single character according to UTF-8 encoding specification          

         $I = $I + 3; // actual byte is 3  

         $n + +; // string length 1  

      }  

      Else if ($ascnum > = 192) // if the ASCII bit is higher than 192,  

      {  

         $returnStr = $returnstr.substr ($sourcestr, $I, 2); // count 2 consecutive characters as a single character according to UTF-8 encoding specification  

         $I = $I + 2; // actual byte is 2  

         $n + +; // string length 1  

      }  

      Else if ($ascnum > = 65 & & $ascnum < = 90) // if it's a capital letter,  

      {  

         $returnstr=$returnstr.substr($sourcestr,$i,1);  

         $I = $I + 1; // the actual number of bytes is still 1  

         $n + +; // but considering the overall beauty, the uppercase letters are counted as a high-order character  

      }  

      Else // in other cases, including lowercase and half angle punctuation,  

      {  

         $returnstr=$returnstr.substr($sourcestr,$i,1);  

         $I = $I + 1; // 1 actual byte count  

         $n = $n + 0.5; // lowercase letters, half width punctuation, and half height characters are width  

      }  

   }  

         if ($str_length>$i){  

          $returnStr = $returnStr. "..."; // add an ellipsis at the end when the length is exceeded  

      }  

    return $returnstr;  

}

In template,
{$brand.brand_description|cut_str=###,10}


String make by ID to makeById

function changestr($string){
    if(!is_string($string)){
        die('please input string.');
    }
    if(strpos($string,'_')){
        $stringArr=explode('_',$string);
        $str='';
        foreach ($stringArr as $v){
            $str .= ucfirst($v);
        }
        return $str;
    }
}

String conversion in JSON format of array string object

/**
 *Object to array
 *
 *@ param object $object object
 * @return array
 */
function object2array(&$object) {
    $object =  json_decode( json_encode( $object),true);
    return  $object;
}


/****Object to JSON array format string*****/
function obj2arr($object) {
    
    $json_object = json_encode($object);
    echo "";
    var_dump($json_object);die;
    $arr = json_decode($json_object, 1);
    return $arr;
}


/****JSON to array*****/
/**
 *[JSON to arr description] JSON to arr traversal turns JSON into an array
 * @param  [type]  $jsonstr [description]
 * @return boolean          [description]
 */
 //Test data: $response = '{"Jingdong" omnichannel "order" ship "update" response ": {" code ":" 0 "," result ":" {\ "code \ \": \ "400 \ \", \ \ "message \ \": \ \ "system exception: cancelled status in logistics component, \ \" success \ \ ": false}"}'} ';

function json_to_arr2($jsonstr)
{
    if (is_string($jsonstr)&&is_array(json_decode($jsonstr, true))) {
        $arr = json_decode($jsonstr, true);
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $kk=>$vv){
                    if(is_string($vv) && is_array(json_decode($vv, true))){
                        $arr[$k][$kk] = json_decode($vv, true);
                    }
                }
            }
            if(is_string($v)&&is_sarray(json_decode($v,true))){
                $arr[$k]=json_decode($v,true);
            }
        }
        return $arr;
    } else {
        die('This is not jsonString!');
    }
}



/**
 *Array to object
 *
 *@ param array $arr array
 * @return object
 */
function array_to_object($arr) {
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
 
    return (object)$arr;
}


$arr = array(
    'name'=>'haima',
    'age'=>32,
    'gender'=>'nan'
);
$a = (object) ($ARR); // array to object
echo '';
var_dump($a);

$jsonstring = json_encode ($array, json_nescaped_unicode); // object to JSON string does not escape Chinese characters
echo '';
var_dump($jsonstring);

$abj = json_decode ($array); // JSON to object
$array = json_decode ($array, true); // JSON to array


echo '';
$B = (array) ($a); // object to array
var_dump($b);

Cast

/**
 *Cast
 * @param string $data
 * @param string $type
 * @return mixed
 */
private function typeCast(&$data, $type)
{
    switch (strtolower($type)) {
        // array
        case 'a':
            $data = (array) $data;
            break;
        // figure
        case 'd':
            $data = (int) $data;
            break;
        // floating point
        case 'f':
            $data = (float) $data;
            break;
        Boolean / Boolean
        case 'b':
            $data = (boolean) $data;
            break;
        // String
        case 's':
        default:
            if (is_scalar($data)) {
                $data = (string) $data;
            } else {
                throw new \InvalidArgumentException('variable type error:' . gettype($data));
            }
    }
}


PHP serialize and return serialize unserialize

Serialize () encodes variables and their values into text
Unserialize() restores the original variable


Create log file

  1. Method 1 (suitable for temporary use):
//Array / string is OK
file_put_contents( 'log.log', date('Y-m-d H:i:s',time()) .' ' . var_export($_REQUEST,true) . "\r\n", FILE_APPEND);
  1. Method two:

For example: www.wdmcake.com/data/log/ date / $file name

/**
*$STR array / str what to write
*$dir STR date folder new folder name for example / www.wdmcake.com/data/log/201806/sms_apiaas
*Name of $file string file example: send log 20180628.log
*/
function wdmlog($str,$dir='log',$file='log')
{
    if (!file_exists(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir))
    {
        make_dir(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir);
    }
    $str = is_array($str) ? var_export($str,true):$str;
       file_put_contents(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir.'/' . $file .'_' . date('Ymd') . '.log', local_date('Y-m-d H:i:s') .' ' . $str . "\r\n", FILE_APPEND);
}
  1. Method three:
function create_log($data,$merchant,$agency,$file='')
{
   If (empty ($merchant)) die ("merchant code cannot be empty");
   If (empty ($agency)) die ("platform code cannot be empty");
   $file_path = ROOT_PATH . 'logdata/'.$merchant.'/'.$agency;
   if(!is_dir($file_path)){
        mkdir($file_path, 0777, true); 
    }    
    file_put_contents($file_path.'/'.$agency.'_' . $file . date('Ymd',time()) . '.log', date('Y-m-d H:i:s',time()) .' ' . var_export($data,true) . "\r\n", FILE_APPEND);
}

Returns the data of one segment of a 2D array

/**
 *[slice description] returns the data of one segment of the two-dimensional array
 *@ param [type] $arr [description] transfer to 2D Association array
 *@ param [type] $Star [description] starting position of interception
 *@ param [type] $length [description] intercepted length
 *@ param [type] $order [description] 0 order - 1 reverse order
 *@ param [type] $preserve [description] keep index relationship true - keep key name false - default. Reset key name
 * @return [type]      [description]
 */
function slice($arr, $star, $length, $order = 0, $preserve = false)
{
    foreach ($arr as $key => $value) {
        $arr[$key] = array_slice($value, $star, $length, $preserve);
    }
    if ($order) {
        return array_reverse($arr);
    }
    return $arr;
}

Example:

'Content-Type=text/html;charset:utf8');
$arr = array(
    [
        'id' => '1',
        'name' = > Li Si ',
        'age' => '21',
        'gender' = > 'male',
    ],
    [
        'id' => '2',
        'name' = > 'Wang Wu',
        'age' => '22',
        'gender' = > 'male',
    ],

);

echo '';
print_r(slice($arr, 0, 2));

// print:
//Print results:
// Array
// (
//     [0] => Array
//         (
//             [id] => 1
//[name] = > Li Si
//         )

//     [1] => Array
//         (
//             [id] => 2
//[name] = > Wang Wu
//         )

// )

Get IP address

  1. Method 1
$_SERVER['REMOTE_ADDR']
  1. Method two
/** 
     *Access IP 
     * Enter description here ... 
     */  
    function getIP() {  
        return isset($_SERVER["HTTP_X_FORWARDED_FOR"])?$_SERVER["HTTP_X_FORWARDED_FOR"]  
        :(isset($_SERVER["HTTP_CLIENT_IP"])?$_SERVER["HTTP_CLIENT_IP"]  
        :$_SERVER["REMOTE_ADDR"]);  
    }
  1. Method three
/**
 *Get the user's real IP address
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /*Take the first non unknown valid IP string in x-forward-for*/
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

PHP restrict IP access only allow specified IP access allow * wildcard to filter IP

/** 
 *Check whether the access IP is the specified allowed IP 
 * Enter description here ... 
 */  
function check_ip(){  
    $ALLOWED_IP=array('192.168.2.*','127.0.0.1','192.168.2.49');  
    $IP=getIP();  
    $check_ip_arr = expand ('.', $IP); // the IP to be detected is split into an array  
    IP Limited  
    if(!in_array($IP,$ALLOWED_IP)) {  
        foreach ($ALLOWED_IP as $val){  
            If (strpos ($Val, '*')! = = false) {// an * substitution was found  
                 $arr=array();//  
                 $arr=explode('.', $val);  
                 $BL = true; // used to record whether there is a successful match in the loop detection  
                 for($i=0;$i<4;$i++){  
                    If ($arr [$I]! = '*' {// does not equal * come in for detection. If it is * symbol substitution, it will not be checked  
                        if($arr[$i]!=$check_ip_arr[$i]){  
                            $bl=false;  
                            Break; // terminate checking this IP and continue checking the next IP  
                        }  
                    }  
                 }//end for   
                 If ($BL) {// if it is true, it will return if one of the matches is successful  
                    return;  
                    die;  
                 }  
            }  
        }//end foreach  
        header('HTTP/1.1 403 Forbidden');  
        echo "Access forbidden";  
        die;  
    }  
}

Get the part of the address path from 0 to the first \ line

function f_dirname($f_path){
    return substr($f_path,0,strrpos($f_path,'\'));
}

Get the file path where the current file is located

define('CUR_API_PATH', rtrim(str_replace('\', '/', dirname(__FILE__)),'/').'/');

Get random string

/**
 *Random character
 *@ param int $length
 *@ param string $type
 *@ param int $convert convert case 1 upper case 0 lower case
 * @return string
 */
function random($length=10, $type='letter', $convert=0)
{
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if(!isset($config[$type])) $type = 'letter';
    $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;
}

Chinese string inversion


Check whether the destination folder exists, and if not, create the directory automatically

/**
 *Check whether the destination folder exists, and if not, create the directory automatically
 *
 * @access      public
 *@ param string folder directory path. Cannot use a URL relative to the site root
 *
 * @return      bool
 */
function make_dir($folder)
{
    $reval = false;

    if (!file_exists($folder))
    {
        /*If the directory does not exist, try to create it*/
        @umask(0);

        /*Split directory paths into arrays*/
        preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);

        /*Treat as a physical path if the first character is /*/
        $base = ($atmp[0][0] == '/') ? '/' : '';

        /*Traversing an array containing path information*/
        foreach ($atmp[1] AS $val)
        {
            if ('' != $val)
            {
                $base .= $val;

                if ('..' == $val || '.' == $val)
                {
                    /*If the directory is. Or*/
                    $base .= '/';

                    continue;
                }
            }
            else
            {
                continue;
            }

            $base .= '/';

            if (!file_exists($base))
            {
                /*Attempt to create directory, continue loop if creation fails*/
                if (@mkdir(rtrim($base, '/'), 0777))
                {
                    @chmod($base, 0777);
                    $reval = true;
                }
            }
        }
    }
    else
    {
        /*The path already exists. Return whether the path is a directory*/
        $reval = is_dir($folder);
    }

    clearstatcache();

    return $reval;
}

Get file modification time by default

function filetime($way,$char='m'){
    date_default_timezone_set('PRC');
    switch($char){
        case 'c':$localtime = date('Y-m-d H:i:s',filectime($way));
        break;
        case 'm':$localtime = date('Y-m-d H:i:s',filemtime($way));
        break;
        case 'a':$localtime = date('Y-m-d H:i:s',fileatime($way));
        break;
    }
    return $localtime;
}

Determine suffix type

function suffixtype($f_path){
    $info = pathinfo($f_path);
    $f_type = 'file';
    switch(strtolower(@$info["extension"])){
        case 'jpg':case 'jpeg':case 'gif':
        case 'png':case 'bmp':$f_type = 'image';break;
        case 'pl':case 'c':case 'cpp':case 'log':case 'asp':case 'php':case 'jsp':case 'txt':case 'xml':case 'html':case 'htm':case 'phtml':case 'jhtml':case 'java':case 'cfg':case 'ini':
        case 'text':case 'bat':$f_type = 'text';break;
    }
    return $f_type;
}

Check file type

/**
 *Check file type
 *
 * @access      public
 *@ param string filename
 *@ param string realName real filename
 *Allowed file types
 * @return      string
 */
function check_file_type($filename, $realname = '', $limit_ext_types = '')
{
    if ($realname)
    {
        $extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
    }
    else
    {
        $extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
    }

    if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false)
    {
        return '';
    }

    $str = $format = '';

    $file = @fopen($filename, 'rb');
    if ($file)
    {
        $STR = @ free ($file, 0x400); // read the first 1024 bytes
        @fclose($file);
    }
    else
    {
        if (stristr($filename, ROOT_PATH) === false)
        {
            if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' ||
                $extname == 'xls' || $extname == 'txt'  || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' ||
                $extname == 'pdf' || $extname == 'rm'   || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' ||
                $extname == 'swf' || $extname == 'chm'  || $extname == 'sql' || $extname == 'cert'|| $extname == 'pptx' || 
                $extname == 'xlsx' || $extname == 'docx')
            {
                $format = $extname;
            }
        }
        else
        {
            return '';
        }
    }

    if ($format == '' && strlen($str) >= 2 )
    {
        if (substr($str, 0, 4) == 'MThd' && $extname != 'txt')
        {
            $format = 'mid';
        }
        elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav')
        {
            $format = 'wav';
        }
        elseif (substr($str ,0, 3) == "\xFF\xD8\xFF")
        {
            $format = 'jpg';
        }
        elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt')
        {
            $format = 'gif';
        }
        elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
        {
            $format = 'png';
        }
        elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt')
        {
            $format = 'bmp';
        }
        elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt')
        {
            $format = 'swf';
        }
        elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0")
        {   // D0CF11E == DOCFILE == Microsoft Office Document
            if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc')
            {
                $format = 'doc';
            }
            elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls')
            {
                $format = 'xls';
            } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt')
            {
                $format = 'ppt';
            }
        } elseif (substr($str ,0, 4) == "PK\x03\x04")
        {
            if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'docx')
            {
                $format = 'docx';
            }
            elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xlsx')
            {
                $format = 'xlsx';
            } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'pptx')
            {
                $format = 'pptx';
            }else
            {
                $format = 'zip';
            }
        } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt')
        {
            $format = 'rar';
        } elseif (substr($str ,0, 4) == "\x25PDF")
        {
            $format = 'pdf';
        } elseif (substr($str ,0, 3) == "\x30\x82\x0A")
        {
            $format = 'cert';
        } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt')
        {
            $format = 'chm';
        } elseif (substr($str ,0, 4) == "\x2ERMF")
        {
            $format = 'rm';
        } elseif ($extname == 'sql')
        {
            $format = 'sql';
        } elseif ($extname == 'txt')
        {
            $format = 'txt';
        }
    }

    if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false)
    {
        $format = '';
    }

    return $format;
}

Gets the file suffix and determines whether it is in the defined array

/**
 *Get the file suffix and judge whether it is legal
 *
 *@ param string $file_name // is the path of a file
 *@ param array $allow_type // array of required file types
 * @return blob
 */
function get_file_suffix($file_name, $allow_type = array())
{
    $file_suffix = strtolower(array_pop(explode('.', $file_name)));
    if (empty($allow_type))
    {
        return $file_suffix;
    }
    else
    {
        if (in_array($file_suffix, $allow_type))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Determine whether the path is a file or a directory

function f_type($f_path){
    return is_dir($f_path)?'dir':suffixtype($f_path);
}

Calculate file or directory byte size

//Calculate file or directory byte size
function bytesize_calc($f_path){
    if(!is_dir($f_path)){
        return sprintf("%u", filesize($f_path));}
    $bytesize = 0;
    $f_arr = scandir($f_path);
    $size = count($f_arr);
    for($i=0;$iif('.'==$f_arr[$i]||'..'==$f_arr[$i])continue;
        $file_or_dir = $f_path.'/'.$f_arr[$i];
        $bytesize += bytesize_calc($file_or_dir);
    }
    return $bytesize;
}
//Get file size
function f_size($f_path){
    return size_formate(bytesize_calc($f_path));
}

Receive asynchronous get messages

$sms_result_data = $_get; // use this
    $param = request() - > param(); // thinkphp5 receive message
    $sms_result_data1 = file_get_contents("php://input");

Get request of curl

function _curl_get($urldata)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$urldata);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    Curl_setopt ($curl, curlopt_ssl_verifypeer, false); // do not verify SSL certificate.
    $data = curl_exec($ch);
    curl_close($ch);
    if ($data)
        return $data;
    else
        return false;
}

Post request of curl

If there is a picture to upload, add the following line of code

curl_file_create(ROOT_PATH.’public’.$value[“goods_img”]);

/**
 * [post description]
 *@ param [type] $URL [requested url]
 *@ param string $post'u data [requested data]
 *@ param integer $timeout
 *@ return [type] $mix [mixed data json|array|obj]
 */
function post($url, $post_data = '', $timeout = 3000)
{
    header("Content-type:text/html;charset=utf-8");
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POST, 1);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $file_contents = curl_exec($ch);
    curl_close($ch); 
    if ($content){
        return $file_contents;
    }else{
        return false;
    }       
}

Post & get request of curl

If there is a picture to upload, add the following line of code

curl_file_create(ROOT_PATH.’public’.$value[“goods_img”]);

  1. Method 1
/**
 * [_curl_post_get description]
 *If $data is idle to get request. HTTPS does not verify the certificate
 * @param  [type]  $url     [url]
 *@ param array $data
 *@ param integer $timeout
 *@ return [type] $mix [mixed data json|array|obj]
 */
function _curl_post($url, $data = '',$timeout = 3000) {
    header("Content-type:text/html;charset=utf-8");
    $ch = curl_init();
    Curl_setopt ($ch, curlopt_url, $URL); // requested URL
    Curl_setopt ($ch, curlopt_header, false); // / whether to carry the head header information ture / error
    Curl_setopt ($ch, curlopt_returntransfer, 1); // return data or print data 0, output 1 directly, return
    Curl_setopt ($ch, curlopt_connecttimeout, $timeout); // set the request timeout time
    //HTTPS request does not validate certificate and hosts method:
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
    //If (1 = = strpos ("$". $URL, "HTTPS: //") // the effect is the same as above
    {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if(!empty($post_data)){
        Curl_setopt ($ch, curlopt_post, 1); // set the post method request, if not written, the default is get method
        Curl_setopt ($ch, curlopt_postfields, $data); // parameter to be passed
    }       

    //Send request and receive data assignment to $data
    $data = curl_exec($ch);  
    //Close request resource
    curl_close($ch);   
    $content = iconv ('gb2312 ',' UTF-8 // ignore ', $data); // modify character code

    if ($content)
        return $content;
    else
        return false;
}
  1. Method two
/**
 * curl access
 * @author rainfer <[email protected]>
 * @param  string $url
 * @param string $type
 * @param boolean $data
 * @param string $err_msg
 * @param int $timeout
 * @param array $cert_info
 * @return string
 */
function go_curl($url, $type, $data = false, &$err_msg = null, $timeout = 20, $cert_info = array())
{
    $type = strtoupper($type);
    if ($type == 'GET' && is_array($data)) {
        $data = http_build_query($data);
    }
    $option = array();
    if ( $type == 'POST' ) {
        $option[CURLOPT_POST] = 1;
    }
    if ($data) {
        if ($type == 'POST') {
            $option[CURLOPT_POSTFIELDS] = $data;
        } elseif ($type == 'GET') {
            $url = strpos($url, '?') !== false ? $url.'&'.$data :  $url.'?'.$data;
        }
    }
    $option[CURLOPT_URL]            = $url;
    $option[CURLOPT_FOLLOWLOCATION] = TRUE;
    $option[CURLOPT_MAXREDIRS]      = 4;
    $option[CURLOPT_RETURNTRANSFER] = TRUE;
    $option[CURLOPT_TIMEOUT]        = $timeout;
    //Set certificate information
    if(!empty($cert_info) && !empty($cert_info['cert_file'])) {
        $option[CURLOPT_SSLCERT]       = $cert_info['cert_file'];
        $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass'];
        $option[CURLOPT_SSLCERTTYPE]   = $cert_info['cert_type'];
    }
    // set CA
    if(!empty($cert_info['ca_file'])) {
        //Check the source of the certificate, 0 means check the validity of the certificate is blocked. 1. Curlopt? Cainfo needs to be set
        $option[CURLOPT_SSL_VERIFYPEER] = 1;
        $option[CURLOPT_CAINFO] = $cert_info['ca_file'];
    } else {
        //Check the source of the certificate, 0 means check the validity of the certificate is blocked. 1. Curlopt? Cainfo needs to be set
        $option[CURLOPT_SSL_VERIFYPEER] = 0;
    }
    $ch = curl_init();
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    $curl_no  = curl_errno($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);
    // error_log
    if($curl_no > 0) {
        if($err_msg !== null) {
            $err_msg = '('.$curl_no.')'.$curl_err;
        }
    }
    return $response;
}
  1. Method three
//Curl simulates post to send request
function curl_sent($url, $postFields = null)
{
    $header = array(
            // 'Content-Type: application/json',
            'Content-Type: application/x-www-form-urlencoded'
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //HTTPS request
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
    {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }

    if (is_array($postFields) && 0 < count($postFields))
    {
        curl_setopt($ch, CURLOPT_POST, true);
        $postMultipart = false;
        foreach ($postFields as $k => $v)
        {
            if ('@' == substr($v, 0, 1))
            {
                $postMultipart = true;
                break;
            }
        }
        unset($k, $v);
        if ($postMultipart) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
        }
    }
    $reponse = curl_exec($ch);

    if (curl_errno($ch))
    {
        throw new JosSdkException(curl_error($ch), 0);
    } else {
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (200 !== $httpStatusCode)
        {
            throw new JosSdkException($reponse, $httpStatusCode);
        }
    }
    curl_close($ch);
    return $reponse;
}

Method four * *:

public $connectTimeout = 0;

    public $readTimeout = 0;
    public function curl($url, $postFields = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($this->readTimeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
        }
        if ($this->connectTimeout) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
        }
        //HTTPS request
        if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        if (is_array($postFields) && 0 < count($postFields))
        {
            $postBodyString = "";
            $postMultipart = false;
            foreach ($postFields as $k => $v)
            {
                If ("@"! = substr ($V, 0, 1)) // determine whether the file is uploaded
                {
                    $postBodyString .= "$k=" . urlencode($v) . "&"; 
                }
                Else // multipart / form data is used for file upload, otherwise www-form-urlencoded is used
                {
                    $postMultipart = true;
                }
            }
            unset($k, $v);
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postMultipart)
            {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            }
            else
            {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
            }
        }
        $reponse = curl_exec($ch);
        $reponse = iconv ('gb2312 ',' UTF-8 // ignore ', $reponse); // modify character encoding
        Create log ('line ',' WDM ',' jdomnic ',' curl ');
        create_log($reponse, 'wdm', 'jdomnic', 'curl');
        if (curl_errno($ch))
        {
            throw new Exception(curl_error($ch),0);
        }
        else
        {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode)
            {
                throw new Exception($reponse,$httpStatusCode);
            }
        }
        curl_close($ch);
        return $reponse;
    }

Judge whether the array type parameter contains empty element value

//$param array
function is_arraynull($param){
    if(!is_array($param)){
        return '0';
    }else{
        foreach ($param as $key => $value) {
            if($value!=''){
                $ret = is_arraynull($value);
            }else{
                return  1;
            }
        }
    }
}

Determine whether necessary parameters are passed in

/**
   *Determine whether necessary parameters are passed in
   * @param  [type] $inter_param [description]
   * @param  [type] $agency      [description]
   * @param  [type] $merchant    [description]
   * @return [type]              [description]
   */
  function judge_parameter($param){
            if(!isset($param['inter_param']) || !isset($param['agency']) || !isset($param['merchant'])){
                return false;
            }
            if(empty($param['inter_param']) || empty($param['agency']) || empty($param['merchant'])){
                return false;
            }
            return true;
  }
From [Haima’s blog] http://www.cnblogs.com/haima/

,

Catalog

  • PHP common custom function class Download
  • PHP sets character encoding to UTF-8
  • Conversion between GB2312 and UTF8
  • Path format (replace double slash with single slash)
  • Get the directory of the current file
  • Printout
  • API return information
  • String truncation
    • Method 1:
    • Method two:
  • String make by ID to makeById
  • String conversion in JSON format of array string object
  • Cast
  • PHP serialize and return serialize unserialize
  • Create log file
  • Returns the data of one segment of a 2D array
  • Get IP address
  • PHP restrict IP access only allow specified IP access allow * wildcard to filter IP
  • Get the part of the address path from 0 to the first \ line
  • Get the file path where the current file is located
  • Get random string
  • Chinese string inversion
  • Check whether the destination folder exists, and if not, create the directory automatically
  • Get file modification time by default
  • Determine suffix type
  • Check file type
  • Gets the file suffix and determines whether it is in the defined array
  • Determine whether the path is a file or a directory
  • Calculate file or directory byte size
  • Receive asynchronous get messages
  • Get request of curl
  • Post request of curl
  • Post & get request of curl
  • Judge whether the array type parameter contains empty element value
  • Determine whether necessary parameters are passed in

PHP common custom function class Download

https://pan.baidu.com/s/18ZuQm5cx3ynQtQqcQgK0Vw


PHP sets character encoding to UTF-8

header("Content-Type: text/html;charset=utf-8");


Conversion between GB2312 and UTF8

Echo iconv ('gb2312 ',' UTF-8 // ignore ', $STR); // change the string encoding from GB2312 to UTF-8
//Ignore means to ignore errors during conversion. Without ignore parameter, all strings following the character cannot be saved.
iconv("UTF-8","GB2312//IGNORE",$data);    
Print_r (iconv_get_encoding()); // get the current page encoding information
// transcoding
function gbk($str){return iconv('utf-8','gbk',$str);}
function utf8($str){return iconv('gbk','utf-8',$str);}

Path format (replace double slash with single slash)

function path_formate($str){
    return str_replace('\\','\',$str);
}

Get the directory of the current file

Method 1:
define('BASE_PATH',rtrim(str_replace('\','/',__DIR__).'/'));
Method two:
define('BASE_DIR', rtrim(str_replace('\', '/', dirname(__FILE__)),'/').'/');

Printout

function dump($var)
{
    echo '';
    print_r($var);
    echo '';
}

function vp($var)
{
    echo '';
    var_dump($var);
    echo '';
}

function dd($var)
{
    echo '';
    var_dump($var);
    echo '';
    die;
}

API return information

/**
*Data return
 *@ param [int] $code [result code 200: normal / 4 * * data problem / 5 * * server problem]
 *@ param [string] $MSG [returned prompt]
 *@ param [array] $data [returned data]
 *@ return [string] [final JSON data]
*/
public function return_msg($code, $msg = '', $data = []) {
 
    /***********Combined data***********/
    $return_data['code'] = $code;
    $return_data['msg']  = $msg;
    $return_data['data'] = $data;
 
    /***********Return information and terminate script***********/
    echo json_encode($return_data,JSON_UNESCAPED_UNICODE);
    die;
}

String truncation

Method 1:

In common.php

//String truncation and display ellipsis exceeded
function subtext($text, $length)
{
if(mb_strlen($text, ‘utf8’) > $length)
return mb_substr($text,0,$length,’utf8′).’ …’;
return $text;
}

In template,
{$tops.title | subtext=18}

Method two:

In common.php

//String truncation

function cut_str($sourcestr,$cutlength)  

{  

   $returnstr='';  

   $i=0;  

   $n=0;  

   $str_length = strlen ($sourcestr); // the number of bytes in the string  

   while (($nand ($i<=$str_length))  

   {  

      $temp_str=substr($sourcestr,$i,1);  

      $ascnum = ord ($temp_str); // get the ASCII code of the $I character in the string  

      If ($ascnum > = 224) // if the ASCII bit height is 224,  

      {  

$returnStr = $returnstr.substr ($sourcestr, $I, 3); // count 3 consecutive characters as a single character according to UTF-8 encoding specification          

         $I = $I + 3; // actual byte is 3  

         $n + +; // string length 1  

      }  

      Else if ($ascnum > = 192) // if the ASCII bit is higher than 192,  

      {  

         $returnStr = $returnstr.substr ($sourcestr, $I, 2); // count 2 consecutive characters as a single character according to UTF-8 encoding specification  

         $I = $I + 2; // actual byte is 2  

         $n + +; // string length 1  

      }  

      Else if ($ascnum > = 65 & & $ascnum < = 90) // if it's a capital letter,  

      {  

         $returnstr=$returnstr.substr($sourcestr,$i,1);  

         $I = $I + 1; // the actual number of bytes is still 1  

         $n + +; // but considering the overall beauty, the uppercase letters are counted as a high-order character  

      }  

      Else // in other cases, including lowercase and half angle punctuation,  

      {  

         $returnstr=$returnstr.substr($sourcestr,$i,1);  

         $I = $I + 1; // 1 actual byte count  

         $n = $n + 0.5; // lowercase letters, half width punctuation, and half height characters are width  

      }  

   }  

         if ($str_length>$i){  

          $returnStr = $returnStr. "..."; // add an ellipsis at the end when the length is exceeded  

      }  

    return $returnstr;  

}

In template,
{$brand.brand_description|cut_str=###,10}


String make by ID to makeById

function changestr($string){
    if(!is_string($string)){
        die('please input string.');
    }
    if(strpos($string,'_')){
        $stringArr=explode('_',$string);
        $str='';
        foreach ($stringArr as $v){
            $str .= ucfirst($v);
        }
        return $str;
    }
}

String conversion in JSON format of array string object

/**
 *Object to array
 *
 *@ param object $object object
 * @return array
 */
function object2array(&$object) {
    $object =  json_decode( json_encode( $object),true);
    return  $object;
}


/****Object to JSON array format string*****/
function obj2arr($object) {
    
    $json_object = json_encode($object);
    echo "";
    var_dump($json_object);die;
    $arr = json_decode($json_object, 1);
    return $arr;
}


/****JSON to array*****/
/**
 *[JSON to arr description] JSON to arr traversal turns JSON into an array
 * @param  [type]  $jsonstr [description]
 * @return boolean          [description]
 */
 //Test data: $response = '{"Jingdong" omnichannel "order" ship "update" response ": {" code ":" 0 "," result ":" {\ "code \ \": \ "400 \ \", \ \ "message \ \": \ \ "system exception: cancelled status in logistics component, \ \" success \ \ ": false}"}'} ';

function json_to_arr2($jsonstr)
{
    if (is_string($jsonstr)&&is_array(json_decode($jsonstr, true))) {
        $arr = json_decode($jsonstr, true);
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $kk=>$vv){
                    if(is_string($vv) && is_array(json_decode($vv, true))){
                        $arr[$k][$kk] = json_decode($vv, true);
                    }
                }
            }
            if(is_string($v)&&is_sarray(json_decode($v,true))){
                $arr[$k]=json_decode($v,true);
            }
        }
        return $arr;
    } else {
        die('This is not jsonString!');
    }
}



/**
 *Array to object
 *
 *@ param array $arr array
 * @return object
 */
function array_to_object($arr) {
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
 
    return (object)$arr;
}


$arr = array(
    'name'=>'haima',
    'age'=>32,
    'gender'=>'nan'
);
$a = (object) ($ARR); // array to object
echo '';
var_dump($a);

$jsonstring = json_encode ($array, json_nescaped_unicode); // object to JSON string does not escape Chinese characters
echo '';
var_dump($jsonstring);

$abj = json_decode ($array); // JSON to object
$array = json_decode ($array, true); // JSON to array


echo '';
$B = (array) ($a); // object to array
var_dump($b);

Cast

/**
 *Cast
 * @param string $data
 * @param string $type
 * @return mixed
 */
private function typeCast(&$data, $type)
{
    switch (strtolower($type)) {
        // array
        case 'a':
            $data = (array) $data;
            break;
        // figure
        case 'd':
            $data = (int) $data;
            break;
        // floating point
        case 'f':
            $data = (float) $data;
            break;
        Boolean / Boolean
        case 'b':
            $data = (boolean) $data;
            break;
        // String
        case 's':
        default:
            if (is_scalar($data)) {
                $data = (string) $data;
            } else {
                throw new \InvalidArgumentException('variable type error:' . gettype($data));
            }
    }
}


PHP serialize and return serialize unserialize

Serialize () encodes variables and their values into text
Unserialize() restores the original variable


Create log file

  1. Method 1 (suitable for temporary use):
//Array / string is OK
file_put_contents( 'log.log', date('Y-m-d H:i:s',time()) .' ' . var_export($_REQUEST,true) . "\r\n", FILE_APPEND);
  1. Method two:

For example: www.wdmcake.com/data/log/ date / $file name

/**
*$STR array / str what to write
*$dir STR date folder new folder name for example / www.wdmcake.com/data/log/201806/sms_apiaas
*Name of $file string file example: send log 20180628.log
*/
function wdmlog($str,$dir='log',$file='log')
{
    if (!file_exists(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir))
    {
        make_dir(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir);
    }
    $str = is_array($str) ? var_export($str,true):$str;
       file_put_contents(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir.'/' . $file .'_' . date('Ymd') . '.log', local_date('Y-m-d H:i:s') .' ' . $str . "\r\n", FILE_APPEND);
}
  1. Method three:
function create_log($data,$merchant,$agency,$file='')
{
   If (empty ($merchant)) die ("merchant code cannot be empty");
   If (empty ($agency)) die ("platform code cannot be empty");
   $file_path = ROOT_PATH . 'logdata/'.$merchant.'/'.$agency;
   if(!is_dir($file_path)){
        mkdir($file_path, 0777, true); 
    }    
    file_put_contents($file_path.'/'.$agency.'_' . $file . date('Ymd',time()) . '.log', date('Y-m-d H:i:s',time()) .' ' . var_export($data,true) . "\r\n", FILE_APPEND);
}

Returns the data of one segment of a 2D array

/**
 *[slice description] returns the data of one segment of the two-dimensional array
 *@ param [type] $arr [description] transfer to 2D Association array
 *@ param [type] $Star [description] starting position of interception
 *@ param [type] $length [description] intercepted length
 *@ param [type] $order [description] 0 order - 1 reverse order
 *@ param [type] $preserve [description] keep index relationship true - keep key name false - default. Reset key name
 * @return [type]      [description]
 */
function slice($arr, $star, $length, $order = 0, $preserve = false)
{
    foreach ($arr as $key => $value) {
        $arr[$key] = array_slice($value, $star, $length, $preserve);
    }
    if ($order) {
        return array_reverse($arr);
    }
    return $arr;
}

Example:

'Content-Type=text/html;charset:utf8');
$arr = array(
    [
        'id' => '1',
        'name' = > Li Si ',
        'age' => '21',
        'gender' = > 'male',
    ],
    [
        'id' => '2',
        'name' = > 'Wang Wu',
        'age' => '22',
        'gender' = > 'male',
    ],

);

echo '';
print_r(slice($arr, 0, 2));

// print:
//Print results:
// Array
// (
//     [0] => Array
//         (
//             [id] => 1
//[name] = > Li Si
//         )

//     [1] => Array
//         (
//             [id] => 2
//[name] = > Wang Wu
//         )

// )

Get IP address

  1. Method 1
$_SERVER['REMOTE_ADDR']
  1. Method two
/** 
     *Access IP 
     * Enter description here ... 
     */  
    function getIP() {  
        return isset($_SERVER["HTTP_X_FORWARDED_FOR"])?$_SERVER["HTTP_X_FORWARDED_FOR"]  
        :(isset($_SERVER["HTTP_CLIENT_IP"])?$_SERVER["HTTP_CLIENT_IP"]  
        :$_SERVER["REMOTE_ADDR"]);  
    }
  1. Method three
/**
 *Get the user's real IP address
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /*Take the first non unknown valid IP string in x-forward-for*/
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

PHP restrict IP access only allow specified IP access allow * wildcard to filter IP

/** 
 *Check whether the access IP is the specified allowed IP 
 * Enter description here ... 
 */  
function check_ip(){  
    $ALLOWED_IP=array('192.168.2.*','127.0.0.1','192.168.2.49');  
    $IP=getIP();  
    $check_ip_arr = expand ('.', $IP); // the IP to be detected is split into an array  
    IP Limited  
    if(!in_array($IP,$ALLOWED_IP)) {  
        foreach ($ALLOWED_IP as $val){  
            If (strpos ($Val, '*')! = = false) {// an * substitution was found  
                 $arr=array();//  
                 $arr=explode('.', $val);  
                 $BL = true; // used to record whether there is a successful match in the loop detection  
                 for($i=0;$i<4;$i++){  
                    If ($arr [$I]! = '*' {// does not equal * come in for detection. If it is * symbol substitution, it will not be checked  
                        if($arr[$i]!=$check_ip_arr[$i]){  
                            $bl=false;  
                            Break; // terminate checking this IP and continue checking the next IP  
                        }  
                    }  
                 }//end for   
                 If ($BL) {// if it is true, it will return if one of the matches is successful  
                    return;  
                    die;  
                 }  
            }  
        }//end foreach  
        header('HTTP/1.1 403 Forbidden');  
        echo "Access forbidden";  
        die;  
    }  
}

Get the part of the address path from 0 to the first \ line

function f_dirname($f_path){
    return substr($f_path,0,strrpos($f_path,'\'));
}

Get the file path where the current file is located

define('CUR_API_PATH', rtrim(str_replace('\', '/', dirname(__FILE__)),'/').'/');

Get random string

/**
 *Random character
 *@ param int $length
 *@ param string $type
 *@ param int $convert convert case 1 upper case 0 lower case
 * @return string
 */
function random($length=10, $type='letter', $convert=0)
{
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if(!isset($config[$type])) $type = 'letter';
    $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;
}

Chinese string inversion


Check whether the destination folder exists, and if not, create the directory automatically

/**
 *Check whether the destination folder exists, and if not, create the directory automatically
 *
 * @access      public
 *@ param string folder directory path. Cannot use a URL relative to the site root
 *
 * @return      bool
 */
function make_dir($folder)
{
    $reval = false;

    if (!file_exists($folder))
    {
        /*If the directory does not exist, try to create it*/
        @umask(0);

        /*Split directory paths into arrays*/
        preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);

        /*Treat as a physical path if the first character is /*/
        $base = ($atmp[0][0] == '/') ? '/' : '';

        /*Traversing an array containing path information*/
        foreach ($atmp[1] AS $val)
        {
            if ('' != $val)
            {
                $base .= $val;

                if ('..' == $val || '.' == $val)
                {
                    /*If the directory is. Or*/
                    $base .= '/';

                    continue;
                }
            }
            else
            {
                continue;
            }

            $base .= '/';

            if (!file_exists($base))
            {
                /*Attempt to create directory, continue loop if creation fails*/
                if (@mkdir(rtrim($base, '/'), 0777))
                {
                    @chmod($base, 0777);
                    $reval = true;
                }
            }
        }
    }
    else
    {
        /*The path already exists. Return whether the path is a directory*/
        $reval = is_dir($folder);
    }

    clearstatcache();

    return $reval;
}

Get file modification time by default

function filetime($way,$char='m'){
    date_default_timezone_set('PRC');
    switch($char){
        case 'c':$localtime = date('Y-m-d H:i:s',filectime($way));
        break;
        case 'm':$localtime = date('Y-m-d H:i:s',filemtime($way));
        break;
        case 'a':$localtime = date('Y-m-d H:i:s',fileatime($way));
        break;
    }
    return $localtime;
}

Determine suffix type

function suffixtype($f_path){
    $info = pathinfo($f_path);
    $f_type = 'file';
    switch(strtolower(@$info["extension"])){
        case 'jpg':case 'jpeg':case 'gif':
        case 'png':case 'bmp':$f_type = 'image';break;
        case 'pl':case 'c':case 'cpp':case 'log':case 'asp':case 'php':case 'jsp':case 'txt':case 'xml':case 'html':case 'htm':case 'phtml':case 'jhtml':case 'java':case 'cfg':case 'ini':
        case 'text':case 'bat':$f_type = 'text';break;
    }
    return $f_type;
}

Check file type

/**
 *Check file type
 *
 * @access      public
 *@ param string filename
 *@ param string realName real filename
 *Allowed file types
 * @return      string
 */
function check_file_type($filename, $realname = '', $limit_ext_types = '')
{
    if ($realname)
    {
        $extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
    }
    else
    {
        $extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
    }

    if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false)
    {
        return '';
    }

    $str = $format = '';

    $file = @fopen($filename, 'rb');
    if ($file)
    {
        $STR = @ free ($file, 0x400); // read the first 1024 bytes
        @fclose($file);
    }
    else
    {
        if (stristr($filename, ROOT_PATH) === false)
        {
            if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' ||
                $extname == 'xls' || $extname == 'txt'  || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' ||
                $extname == 'pdf' || $extname == 'rm'   || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' ||
                $extname == 'swf' || $extname == 'chm'  || $extname == 'sql' || $extname == 'cert'|| $extname == 'pptx' || 
                $extname == 'xlsx' || $extname == 'docx')
            {
                $format = $extname;
            }
        }
        else
        {
            return '';
        }
    }

    if ($format == '' && strlen($str) >= 2 )
    {
        if (substr($str, 0, 4) == 'MThd' && $extname != 'txt')
        {
            $format = 'mid';
        }
        elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav')
        {
            $format = 'wav';
        }
        elseif (substr($str ,0, 3) == "\xFF\xD8\xFF")
        {
            $format = 'jpg';
        }
        elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt')
        {
            $format = 'gif';
        }
        elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
        {
            $format = 'png';
        }
        elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt')
        {
            $format = 'bmp';
        }
        elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt')
        {
            $format = 'swf';
        }
        elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0")
        {   // D0CF11E == DOCFILE == Microsoft Office Document
            if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc')
            {
                $format = 'doc';
            }
            elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls')
            {
                $format = 'xls';
            } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt')
            {
                $format = 'ppt';
            }
        } elseif (substr($str ,0, 4) == "PK\x03\x04")
        {
            if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'docx')
            {
                $format = 'docx';
            }
            elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xlsx')
            {
                $format = 'xlsx';
            } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'pptx')
            {
                $format = 'pptx';
            }else
            {
                $format = 'zip';
            }
        } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt')
        {
            $format = 'rar';
        } elseif (substr($str ,0, 4) == "\x25PDF")
        {
            $format = 'pdf';
        } elseif (substr($str ,0, 3) == "\x30\x82\x0A")
        {
            $format = 'cert';
        } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt')
        {
            $format = 'chm';
        } elseif (substr($str ,0, 4) == "\x2ERMF")
        {
            $format = 'rm';
        } elseif ($extname == 'sql')
        {
            $format = 'sql';
        } elseif ($extname == 'txt')
        {
            $format = 'txt';
        }
    }

    if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false)
    {
        $format = '';
    }

    return $format;
}

Gets the file suffix and determines whether it is in the defined array

/**
 *Get the file suffix and judge whether it is legal
 *
 *@ param string $file_name // is the path of a file
 *@ param array $allow_type // array of required file types
 * @return blob
 */
function get_file_suffix($file_name, $allow_type = array())
{
    $file_suffix = strtolower(array_pop(explode('.', $file_name)));
    if (empty($allow_type))
    {
        return $file_suffix;
    }
    else
    {
        if (in_array($file_suffix, $allow_type))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Determine whether the path is a file or a directory

function f_type($f_path){
    return is_dir($f_path)?'dir':suffixtype($f_path);
}

Calculate file or directory byte size

//Calculate file or directory byte size
function bytesize_calc($f_path){
    if(!is_dir($f_path)){
        return sprintf("%u", filesize($f_path));}
    $bytesize = 0;
    $f_arr = scandir($f_path);
    $size = count($f_arr);
    for($i=0;$iif('.'==$f_arr[$i]||'..'==$f_arr[$i])continue;
        $file_or_dir = $f_path.'/'.$f_arr[$i];
        $bytesize += bytesize_calc($file_or_dir);
    }
    return $bytesize;
}
//Get file size
function f_size($f_path){
    return size_formate(bytesize_calc($f_path));
}

Receive asynchronous get messages

$sms_result_data = $_get; // use this
    $param = request() - > param(); // thinkphp5 receive message
    $sms_result_data1 = file_get_contents("php://input");

Get request of curl

function _curl_get($urldata)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$urldata);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    Curl_setopt ($curl, curlopt_ssl_verifypeer, false); // do not verify SSL certificate.
    $data = curl_exec($ch);
    curl_close($ch);
    if ($data)
        return $data;
    else
        return false;
}

Post request of curl

If there is a picture to upload, add the following line of code

curl_file_create(ROOT_PATH.’public’.$value[“goods_img”]);

/**
 * [post description]
 *@ param [type] $URL [requested url]
 *@ param string $post'u data [requested data]
 *@ param integer $timeout
 *@ return [type] $mix [mixed data json|array|obj]
 */
function post($url, $post_data = '', $timeout = 3000)
{
    header("Content-type:text/html;charset=utf-8");
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POST, 1);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $file_contents = curl_exec($ch);
    curl_close($ch); 
    if ($content){
        return $file_contents;
    }else{
        return false;
    }       
}

Post & get request of curl

If there is a picture to upload, add the following line of code

curl_file_create(ROOT_PATH.’public’.$value[“goods_img”]);

  1. Method 1
/**
 * [_curl_post_get description]
 *If $data is idle to get request. HTTPS does not verify the certificate
 * @param  [type]  $url     [url]
 *@ param array $data
 *@ param integer $timeout
 *@ return [type] $mix [mixed data json|array|obj]
 */
function _curl_post($url, $data = '',$timeout = 3000) {
    header("Content-type:text/html;charset=utf-8");
    $ch = curl_init();
    Curl_setopt ($ch, curlopt_url, $URL); // requested URL
    Curl_setopt ($ch, curlopt_header, false); // / whether to carry the head header information ture / error
    Curl_setopt ($ch, curlopt_returntransfer, 1); // return data or print data 0, output 1 directly, return
    Curl_setopt ($ch, curlopt_connecttimeout, $timeout); // set the request timeout time
    //HTTPS request does not validate certificate and hosts method:
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
    //If (1 = = strpos ("$". $URL, "HTTPS: //") // the effect is the same as above
    {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if(!empty($post_data)){
        Curl_setopt ($ch, curlopt_post, 1); // set the post method request, if not written, the default is get method
        Curl_setopt ($ch, curlopt_postfields, $data); // parameter to be passed
    }       

    //Send request and receive data assignment to $data
    $data = curl_exec($ch);  
    //Close request resource
    curl_close($ch);   
    $content = iconv ('gb2312 ',' UTF-8 // ignore ', $data); // modify character code

    if ($content)
        return $content;
    else
        return false;
}
  1. Method two
/**
 * curl access
 * @author rainfer <[email protected]>
 * @param  string $url
 * @param string $type
 * @param boolean $data
 * @param string $err_msg
 * @param int $timeout
 * @param array $cert_info
 * @return string
 */
function go_curl($url, $type, $data = false, &$err_msg = null, $timeout = 20, $cert_info = array())
{
    $type = strtoupper($type);
    if ($type == 'GET' && is_array($data)) {
        $data = http_build_query($data);
    }
    $option = array();
    if ( $type == 'POST' ) {
        $option[CURLOPT_POST] = 1;
    }
    if ($data) {
        if ($type == 'POST') {
            $option[CURLOPT_POSTFIELDS] = $data;
        } elseif ($type == 'GET') {
            $url = strpos($url, '?') !== false ? $url.'&'.$data :  $url.'?'.$data;
        }
    }
    $option[CURLOPT_URL]            = $url;
    $option[CURLOPT_FOLLOWLOCATION] = TRUE;
    $option[CURLOPT_MAXREDIRS]      = 4;
    $option[CURLOPT_RETURNTRANSFER] = TRUE;
    $option[CURLOPT_TIMEOUT]        = $timeout;
    //Set certificate information
    if(!empty($cert_info) && !empty($cert_info['cert_file'])) {
        $option[CURLOPT_SSLCERT]       = $cert_info['cert_file'];
        $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass'];
        $option[CURLOPT_SSLCERTTYPE]   = $cert_info['cert_type'];
    }
    // set CA
    if(!empty($cert_info['ca_file'])) {
        //Check the source of the certificate, 0 means check the validity of the certificate is blocked. 1. Curlopt? Cainfo needs to be set
        $option[CURLOPT_SSL_VERIFYPEER] = 1;
        $option[CURLOPT_CAINFO] = $cert_info['ca_file'];
    } else {
        //Check the source of the certificate, 0 means check the validity of the certificate is blocked. 1. Curlopt? Cainfo needs to be set
        $option[CURLOPT_SSL_VERIFYPEER] = 0;
    }
    $ch = curl_init();
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    $curl_no  = curl_errno($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);
    // error_log
    if($curl_no > 0) {
        if($err_msg !== null) {
            $err_msg = '('.$curl_no.')'.$curl_err;
        }
    }
    return $response;
}
  1. Method three
//Curl simulates post to send request
function curl_sent($url, $postFields = null)
{
    $header = array(
            // 'Content-Type: application/json',
            'Content-Type: application/x-www-form-urlencoded'
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //HTTPS request
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
    {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }

    if (is_array($postFields) && 0 < count($postFields))
    {
        curl_setopt($ch, CURLOPT_POST, true);
        $postMultipart = false;
        foreach ($postFields as $k => $v)
        {
            if ('@' == substr($v, 0, 1))
            {
                $postMultipart = true;
                break;
            }
        }
        unset($k, $v);
        if ($postMultipart) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
        }
    }
    $reponse = curl_exec($ch);

    if (curl_errno($ch))
    {
        throw new JosSdkException(curl_error($ch), 0);
    } else {
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (200 !== $httpStatusCode)
        {
            throw new JosSdkException($reponse, $httpStatusCode);
        }
    }
    curl_close($ch);
    return $reponse;
}

Method four * *:

public $connectTimeout = 0;

    public $readTimeout = 0;
    public function curl($url, $postFields = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($this->readTimeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
        }
        if ($this->connectTimeout) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
        }
        //HTTPS request
        if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        if (is_array($postFields) && 0 < count($postFields))
        {
            $postBodyString = "";
            $postMultipart = false;
            foreach ($postFields as $k => $v)
            {
                If ("@"! = substr ($V, 0, 1)) // determine whether the file is uploaded
                {
                    $postBodyString .= "$k=" . urlencode($v) . "&"; 
                }
                Else // multipart / form data is used for file upload, otherwise www-form-urlencoded is used
                {
                    $postMultipart = true;
                }
            }
            unset($k, $v);
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postMultipart)
            {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            }
            else
            {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
            }
        }
        $reponse = curl_exec($ch);
        $reponse = iconv ('gb2312 ',' UTF-8 // ignore ', $reponse); // modify character encoding
        Create log ('line ',' WDM ',' jdomnic ',' curl ');
        create_log($reponse, 'wdm', 'jdomnic', 'curl');
        if (curl_errno($ch))
        {
            throw new Exception(curl_error($ch),0);
        }
        else
        {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode)
            {
                throw new Exception($reponse,$httpStatusCode);
            }
        }
        curl_close($ch);
        return $reponse;
    }

Judge whether the array type parameter contains empty element value

//$param array
function is_arraynull($param){
    if(!is_array($param)){
        return '0';
    }else{
        foreach ($param as $key => $value) {
            if($value!=''){
                $ret = is_arraynull($value);
            }else{
                return  1;
            }
        }
    }
}

Determine whether necessary parameters are passed in

/**
   *Determine whether necessary parameters are passed in
   * @param  [type] $inter_param [description]
   * @param  [type] $agency      [description]
   * @param  [type] $merchant    [description]
   * @return [type]              [description]
   */
  function judge_parameter($param){
            if(!isset($param['inter_param']) || !isset($param['agency']) || !isset($param['merchant'])){
                return false;
            }
            if(empty($param['inter_param']) || empty($param['agency']) || empty($param['merchant'])){
                return false;
            }
            return true;
  }