A detailed explanation of some of the more common php self built functions in php projects

  • 2020-06-07 04:20:23
  • OfStack

The following php functions are the most commonly used project development functions of it motivation. These functions are used in many projects and are also quite common.
1. Processing function of request interface

/** 
 * curl Access program interface  
 * @param string 
 * @return array 
 */  
function getCurlDate($url, $datas, $key) {  
    $datas['time'] = $_SERVER['REQUEST_TIME'] + 300;  
    $post_data['post'] = urlencode(authcode(serialize($datas), "ENCODE", $key));  
//    echo $url;  
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    //  We are in POST Data!   
    curl_setopt($ch, CURLOPT_POST, 1);  
    //  the post Plus the variable of   
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);  
    $output = curl_exec($ch);  
 //   dump(curl_error($ch));  
    curl_close($ch);  
    return json_decode($output, true);  
}  

2. Get the file extension

/** 
 * @ Gets the file extension  
 * @$pic string  Image path  
 */  
function get_file_ext($pic) {  
    return substr($pic, strrpos($pic, '.') + 1);  
}  

3. Reversible encryption and decryption functions

/** 
 *  String encryption  
 * @param   $string      Characters to encrypt  
 * @param   $operation   Encrypt or decrypt  
 * @param   $key         Site encryption key To prevent cracking  
 * @return  string 
 */  
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {  
    $ckey_length = 4;  
    $key = md5($key ? $key : '^www.itokit.com$');  
    $keya = md5(substr($key, 0, 16));  
    $keyb = md5(substr($key, 16, 16));  
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';  

    $cryptkey = $keya . md5($keya . $keyc);  
    $key_length = strlen($cryptkey);  

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;  
    $string_length = strlen($string);  

    $result = '';  
    $box = range(0, 255);  

    $rndkey = array();  
    for ($i = 0; $i <= 255; $i++) {  
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);  
    }  

    for ($j = $i = 0; $i < 256; $i++) {  
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;  
        $tmp = $box[$i];  
        $box[$i] = $box[$j];  
        $box[$j] = $tmp;  
    }  

    for ($a = $j = $i = 0; $i < $string_length; $i++) {  
        $a = ($a + 1) % 256;  
        $j = ($j + $box[$a]) % 256;  
        $tmp = $box[$a];  
        $box[$a] = $box[$j];  
        $box[$j] = $tmp;  
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));  
    }  

    if ($operation == 'DECODE') {  
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {  
            return substr($result, 26);  
        } else {  
            return '';  
        }  
    } else {  
        return $keyc . str_replace('=', '', base64_encode($result));  
    }  
}  

4. Rotate the string to base 106

/** 
*  The string to turn 106 Into the system  
* @param unknown_type $s 
*/  
function str2hex($s) {  
  $r = "";  
  $hexes = array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");  
  for ($i=0; $i<strlen($s); $i++)  
  $r .= ($hexes [(ord($s{$i}) >> 4)] . $hexes [(ord($s{$i}) & 0xf)]);  
  return $r;  
} 

Hex string

/** 
* 106 Hexadecimal string  
* @param unknown_type $s 
*/  
function hex2str($s) {  
  $r = "";  
  for ( $i = 0; $i<strlen($s); $i += 2)  
  {  
    $x1 = ord($s{$i});  
    $x1 = ($x1>=48 && $x1<58) ? $x1-48 : $x1-97+10;  
    $x2 = ord($s{$i+1});  
    $x2 = ($x2>=48 && $x2<58) ? $x2-48 : $x2-97+10;  
    $r .= chr((($x1 << 4) & 0xf0) | ($x2 & 0x0f));  
  }  
  return $r;  
}  

6. Returns a string or array processed by addslashes

/** 
*  Return to the addslashes A string or array that has been processed  
* @param $string  A string or array that needs to be processed  
* @return mixed 
*/  
function new_addslashes($string){  
  if(!is_array($string)) return addslashes($string);  
  foreach($string as $key => $val) $string[$key] = new_addslashes($val);  
  return $string;  
}  

/**/  
function addslashes_deep($string)  
{  
  return is_array($string) ? array_map('addslashes_deep', $string) : addslashes($string);  
}  

7. Returns a string or array processed by stripslashes

/** 
*  Return to the stripslashes A string or array that has been processed  
* @param $string  A string or array that needs to be processed  
* @return mixed 
*/  
function new_stripslashes($string) {  
  if(!is_array($string)) return stripslashes($string);  
  foreach($string as $key => $val) $string[$key] = new_stripslashes($val);  
  return $string;  
}  
/**/  
function stripslashes_deep($string)  
{  
  return is_array($string) ? array_map('stripslashes_deep', $string) : stripslashes($string);  
}  

8. Returns a string or array processed by htmlspecialchars

/** 
*  Return to the  htmlspecialchars  A string or array that has been processed  
* @param $string  A string or array that needs to be processed  
* @return mixed 
*/  
function new_html_special_chars($string) {  
  if(!is_array($string)) return htmlspecialchars($string);  
  foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);  
  return $string;  
}  

9. Get request ip

/** 
 *  Get request ip 
 * 
 * @return ip address  
 */  
function ip() {  
  if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {  
    $ip = getenv('HTTP_CLIENT_IP');  
  } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {  
    $ip = getenv('HTTP_X_FORWARDED_FOR');  
  } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {  
    $ip = getenv('REMOTE_ADDR');  
  } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {  
    $ip = $_SERVER['REMOTE_ADDR'];  
  }  
  return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';  
}  

10. Character interception supports UTF8/GBK

/** 
*  Character interception   support UTF8/GBK 
* @param $string 
* @param $length 
* @param $dot 
*/  
function str_cut($string, $length, $dot = '...') {  
  $strlen = strlen($string);  
  if($strlen <= $length) return $string;  
  $string = str_replace(array(' ',' ', '&', '"', ''', ' " ', ' " ', ' - ', '<', '>', ' ・ ', ' ... '), array(' ∵ ',' ', '&', '"', "'", ' " ', ' " ', ' - ', '<', '>', ' ・ ', ' ... '), $string);  
  $strcut = '';  
  if(strtolower(CHARSET) == 'utf-8') {  
    $length = intval($length-strlen($dot)-$length/3);  
    $n = $tn = $noc = 0;  
    while($n < strlen($string)) {  
      $t = ord($string[$n]);  
      if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {  
        $tn = 1; $n++; $noc++;  
      } elseif(194 <= $t && $t <= 223) {  
        $tn = 2; $n += 2; $noc += 2;  
      } elseif(224 <= $t && $t <= 239) {  
        $tn = 3; $n += 3; $noc += 2;  
      } elseif(240 <= $t && $t <= 247) {  
        $tn = 4; $n += 4; $noc += 2;  
      } elseif(248 <= $t && $t <= 251) {  
        $tn = 5; $n += 5; $noc += 2;  
      } elseif($t == 252 || $t == 253) {  
        $tn = 6; $n += 6; $noc += 2;  
      } else {  
        $n++;  
      }  
      if($noc >= $length) {  
        break;  
      }  
    }  
    if($noc > $length) {  
      $n -= $tn;  
    }  
    $strcut = substr($string, 0, $n);  
    $strcut = str_replace(array(' ∵ ', '&', '"', "'", ' " ', ' " ', ' - ', '<', '>', ' ・ ', ' ... '), array(' ', '&', '"', ''', ' " ', ' " ', ' - ', '<', '>', ' ・ ', ' ... '), $strcut);  
  } else {  
    $dotlen = strlen($dot);  
    $maxi = $length - $dotlen - 1;  
    $current_str = '';  
    $search_arr = array('&',' ', '"', "'", ' " ', ' " ', ' - ', '<', '>', ' ・ ', ' ... ',' ∵ '); 
    $replace_arr = array('&',' ', '"', ''', ' " ', ' " ', ' - ', '<', '>', ' ・ ', ' ... ',' ');  
    $search_flip = array_flip($search_arr);  
    for ($i = 0; $i < $maxi; $i++) {  
      $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];  
      if (in_array($current_str, $search_arr)) {  
        $key = $search_flip[$current_str];  
        $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);  
      }  
      $strcut .= $current_str;  
    }  
  }  
  return $strcut.$dot;  
}  

11. Generate random strings

/** 
*  Generate random strings  
* 
* @param        int                $length     The length of the output   
* @param        string         $chars      optional   By default,  0123456789 
* @return     string          string  
*/  
function random($length, $chars = '0123456789') {  
  $hash = '';  
  $max = strlen($chars) - 1;  
  for($i = 0; $i < $length; $i++) {  
    $hash .= $chars[mt_rand(0, $max)];  
  }  
  return $hash;  
}  

12. Converts strings to arrays

/** 
*  Converts a string to an array  
* 
* @param  string  $data   string  
* @return  array   Returns the array format, if, data Is null, returns an empty array  
*/  
function string2array($data) {  
  if($data == '') return array();  
  eval("\$array = $data;");  
  return $array;  
}  

13. Convert an array to a string

/** 
*  Converts an array to a string  
* 
* @param  array  $data     An array of  
* @param  bool  $isformdata   If it is 0 , do not use new_stripslashes Processing, optional parameter, default is 1 
* @return  string   Returns a string if, data Is null, returns null  
*/  
function array2string($data, $isformdata = 1) {  
  if($data == '') return '';  
  if($isformdata) $data = new_stripslashes($data);  
  return addslashes(var_export($data, TRUE));  
}  

14. Converts the number of bytes to other units

/** 
*  Converts the number of bytes to other units  
* 
* 
* @param        string        $filesize         Byte size  
* @return        string         Returns the size of  
*/  
function sizecount($filesize) {  
        if ($filesize >= 1073741824) {  
                $filesize = round($filesize / 1073741824 * 100) / 100 .' GB';  
        } elseif ($filesize >= 1048576) {  
                $filesize = round($filesize / 1048576 * 100) / 100 .' MB';  
        } elseif($filesize >= 1024) {  
                $filesize = round($filesize / 1024 * 100) / 100 . ' KB';  
        } else {  
                $filesize = $filesize.' Bytes';  
        }  
        return $filesize;  
}  


Related articles: