PHP Common Tools class encyclopedia with all code download _php instance

Source: Internet
Author: User

Nonsense not much said, directly to everyone paste PHP code, the specific code as follows:

<?php/** * Helper class * @author Www.shouce.ren * */class Helper {/** * To determine the current server system * @return string/public static fun Ction Getos () {if (Path_separator = ': ') {return ' Linux ';}
else{return ' Windows ';}  /** * Current Subtleties * @return number/public static function Microtime_float () {list ($usec, $sec) = Explode ("", Microtime
() );
Return ((float) $usec + (float) $sec); /** * Cutting Utf-8 format strings (one character or one byte) * * @author Zhao Jinhan * @version v1.0.0 */public static function truncate_utf8_s Tring ($string, $length, $etc = ' ... ') {$result = '; $string = Html_entity_decode (Trim (strip_tags ($string)), Ent_
Quotes, ' UTF-8 ');
$strlen = strlen ($string); for ($i = 0; (($i < $strlen) && ($length > 0)); $i + +) {if ($number = Strpos (Str_pad (Decbin (Ord (substr ($string, $i, 1)), 8, ' 0 ', str_pad_left), ' 0 ') {i
F ($length < 1.0) {break;} $result. = substr ($string, $i, $number);
$length-= 1.0;
$i + + $number-1; else {$result. = substr ($stRing, $i, 1);
$length-= 0.5;
} $result = Htmlspecialchars ($result, ent_quotes, ' UTF-8 ');
if ($i < $strlen) {$result. = $etc;} return $result; /** * Traverse Folder * @param string $dir * @param boolean $all True indicates the recursive traversal * @return array/public static function Scanfdir ($di R= ', $all = False, & $ret = Array ()) {if (false!== ($handle = Opendir ($dir))) {While false!== ($file = Readdi R ($handle)) {if!in_array ($file, Array ('. ', ' ... ', '. Git ', ' gitignore ', '. svn ', '. htaccess ', '. BuildPath ', '. Project ) {$cur _path = $dir. '/' .
$file; if (Is_dir ($cur _path)) {$ret [' dirs '] = $cur _path; $all && self::scanfdir ($cur _path, $all, $ret);} else {$r
Et [' Files '] [] = $cur _path;
}} closedir ($handle);
return $ret;  /** * Mail Send * @param string $toemail * @param string $subject * @param string $message * @return Boolean/public static function SendMail ($toemail = ', $subject = ', $message = ') {$mailer = Yii::createcomponent (' application.extensions . MaIler.
Emailer ');
Mail configuration $mailer->setlanguage (' zh_cn '); $mailer->host = Yii::app ()->params[' emailhost ']; Send mail server $mailer->port = Yii::app ()->params[' Emailport ']; Mail port $mailer->timeout = Yii::app ()->params[' emailtimeout '];//mail send timeout $mailer->contenttype = ' text/html '
;//Set HTML format $mailer->smtpauth = true;
$mailer->username = Yii::app ()->params[' emailusername '];
$mailer->password = Yii::app ()->params[' Emailpassword '];
$mailer->issmtp (); $mailer->from = $mailer->username; Sender's mailbox $mailer->fromname = Yii::app ()->params[' emailformname '];
The sender's name $mailer->addreplyto ($mailer->username);
$mailer->charset = ' UTF-8 ';
Add Mail Log $modelMail = new Maillog ();
$modelMail->accept = $toemail;
$modelMail->subject = $subject;
$modelMail->message = $message;
$modelMail->send_status = ' waiting ';
$modelMail->save ();
Send mail $mailer->addaddress ($toemail);
$mailer->subject = $subject;
$mailer->body = $message; If ($mailer->send () = = True)  {$modelMail->times = $modelMail->times + 1; $modelMail->send_status = ' success '; $modelMail->save (); return
True else {$error = $mailer->errorinfo; $modelMail->times = $modelMail->times + 1; $modelMail->send_status = ' FA
Iled ';
$modelMail->error = $error;
$modelMail->save ();
return false; }/** * Determines whether the string is Utf-8 or gb2312 * @param unknown $STR * @param string $default * @return string/public static function U
  tf8_gb2312 ($str, $default = ' gb2312 ') {$str = Preg_replace ("/[\x01-\x7f]+/", "", $str);
  if (empty ($STR)) return $default; $preg = Array ("gb2312" => "/^ ([\xa1-\xf7][\xa0-\xfe]) +$/",//regular to determine if gb2312 "Utf-8" => "/^[\x{4e00}-\x{9fa5"}
  ]+$/u ",//The regular judge is the Chinese character (the UTF8 code condition), this scope actually already contains the traditional Chinese text);
  if ($default = = ' gb2312 ') {$option = ' utf-8 ';
  else {$option = ' gb2312 ';
  } if (!preg_match ($preg [$default], $str)) {return $option;
  $str = @iconv ($default, $option, $STR); Can't turn into$option, the original is not $default if (empty ($STR)) {return $option;
return $default; /** * Utf-8 and gb2312 automatic conversion * @param unknown $string * @param string $outEncoding * @return unknown|string/public static F  Unction safeencoding ($string, $outEncoding = ' UTF-8 ') {$encoding = "UTF-8"; for ($i = 0; $i < strlen ($string); $i + +) {if (ord ($string {$i}) < 128) continue; if ((Ord ($string {$i}) & 224 = = 224) {//The first byte is judged by $char = $strin
G {+ + $i}; if ((Ord ($char) & 128) = = 128) {//The second byte is judged by $char = $string {+ + $i}; if ((Ord ($char) & 128) = = 128) {$enc
oding = "UTF-8";
Break }} if ((Ord ($string {$i}) & 192 = = 192) {//The first byte is judged by $char = $string {+ + $i}; if (Ord ($char) & 128) =
= 128) {//The second byte is judged by $encoding = "GB2312"; break;}}
} if (Strtoupper ($encoding) = = Strtoupper ($outEncoding)) return $string;
else return @iconv ($encoding, $outEncoding, $string); /** * Returns all values of a key name in a two-dimensional array * @param input $array * @param string $key * @retuRN Array */public static function Array_key_values ($array =array (), $key = ') {$ret = array (); foreach (array) $array as $
K=> $v) {$ret [$k] = $v [$key];} return $ret; /** * To determine if a file/directory is writable (replace the system's own is_writeable function) * @param string $file File/directory * @return Boolean/public static function Is_ Writeable ($file) {if (Is_dir ($file)) {$dir = $file; if ($fp = @fopen ("$dir/test.txt", ' W ')) {@fclose ($fp); @unlink ("$dir
/test.txt ");
$writeable = 1; else {$writeable = 0;}}
else {if ($fp = @fopen ($file, ' A + ')) {@fclose ($fp); $writeable = 1;} else {$writeable = 0;}} return $writeable; /** * Format unit/static public function Byteformat ($size, $dec = 2) {$a = array ("B", "KB", "MB", "GB", "TB", "PB
" );
$pos = 0; while ($size >= 1024) {$size/= 1024; $pos + +;} return round ($size, $dec). " " .
$a [$pos]; 
/** * dropdown box, radio button Automatically select * * @param $string input character * @param $param condition * @param $type Type * Selected Checked * @return String * * static Public function selected ($string, $param = 1, $type = ' select ') {$true = false; if (Is_array ($param)) {$true = In_array ($string, $param);}
ElseIf ($string = = $param) {$true = true;} $return = '; if ($true) $return = $type = ' SELECT '?
' Selected= ' selected ': ' checked= ' checked ';
Echo $return; /** * Download Remote picture * @param string $url The absolute URL of a picture @param string $filepath The full path of the file (for example,/www/images/test), which is automatically based on the picture URL and HTTP header information Fixed picture suffix * @param string $filename file name to be saved (without extension) * @return mixed download successfully returns an array that describes picture information, returns False when download fails * */static public function Downloadimage ($url, $filepath, $filename) {//The header information returned by the server $responseHeaders = Array ();
Name $ext = ';
$ch = Curl_init ($url);
Setting the value returned by Curl_exec contains HTTP headers curl_setopt ($ch, Curlopt_header, 1);
Setting the value returned by Curl_exec contains HTTP content curl_setopt ($ch, Curlopt_returntransfer, 1);
Set grab jump (http 301,302) after the page curl_setopt ($ch, curlopt_followlocation, 1);
Set the maximum number of HTTP redirects curl_setopt ($ch, Curlopt_maxredirs, 3);
The data returned by the server (including HTTP header information and content) $html = curl_exec ($ch); Get information on this crawl $httpinfo = Curl_getinfo ($ch);
Curl_close ($ch); if ($html!== false) {//detach the header and body of the response, because the server may have used 302 jumps, it is necessary to separate the string from the list of $HTTPARR = explode = \r\n\r\n, $
HTML, 2 + $httpinfo [' redirect_count ']);
The penultimate paragraph is the server's last response HTTP header $header = $HTTPARR [Count ($HTTPARR)-2];
The penultimate paragraph is the last time the server response $body = $HTTPARR [Count ($HTTPARR)-1];
$header. = "\ r \ n";
Gets the header information for the last response Preg_match_all ('/([a-z0-9-_]+): \s* ([^\r\n]+) \r\n/i ', $header, $matches);  if (!empty ($matches) && count ($matches) = = 3 &&!empty ($matches [1]) &&!empty ($matches [1])) {for ($i = 0; $i < count ($matches [1]); $i + +)
{if (array_key_exists ($i, $matches [2])) {$responseHeaders [$matches [1][$i]] = $matches [2][$i];}} //Get the picture suffix name if (0 < Preg_match (' {(?: [^\/\\\\]+) \. jpg|jpeg|gif|png|bmp) $}i ', $url, $matches)} {$originalfilename = $matches [0]; $ext = $matches [1];} else {if (array_key_ Exists (' Content-type ', $responseHeaders)) {if (0 < Preg_match (' {image/(\w+)}i '), $responseHeaders ['Content-type '], $extmatches)) {$ext = $extmatches [1];}} //Save File if (!empty ($ext)) {//If directory does not exist, first create directory if (!is_dir ($filepath)) {mkdir ($filepath, 0777, True);} $filepath. = '/'. $f Ilename. ".
$ext ";
$local _file = fopen ($filepath, ' w '); if (false!== $local _file) {if (False!== fwrite ($local _file, $body)) {fclose ($local _file); $sizeinfo = getimagesize ($fi
Lepath); Return Array (' filepath ' => realpath ($filepath), ' width ' => $sizeinfo [0], ' height ' => $sizeinfo [1], '
Orginalfilename ' => $originalfilename, ' filename ' => pathinfo ($filepath, pathinfo_basename));
}}} return false; /** * Find out if IP is inside a segment * @param string $ip IP * @param to query $arrIP banned IP * @return boolean/public static function Ipacc ESS ($ip = ' 0.0.0.0 ', $arrIP = Array ()) {$access = true; $ip && $arr _cur_ip = Explode ('. ', $ip); foreach (array) $arrI P as $key => $value) {if ($value = = ' *.*.*.* ') {$access = false;//disable all break;} $tmp _arr = Explode ('. ', $value); if ($ar R_cur_ip[0] = = $tmp _arr[0]) && ($arr _cur_ip[1] = = $tmp _arr[1])) {//First two paragraphs the same if (($arr _cur_ip[2] = = $tmp _arr[2]) | | ($tmp _arr[2] = = ' * ')) {//Third paragraph is * or the same if (($arr _cur_ip[3] = = $tmp _arr[3]) | | ($tmp _arr[3] = = ' * '))
{//The fourth paragraph is * or the same $access = false;//The break is disabled if the IP column is blocked;}
}} return $access; /** * @param string $string The original text or ciphertext * @param string $operation operation (ENCODE |  DECODE), the default is DECODE * @param string $key key * @param int $expiry ciphertext validity period, encryption time valid, unit seconds, 0 for permanent valid * @return string processing of the original or after
Base64_encode processed Ciphertext * * @example * * $a = authcode (' abc ', ' Encode ', ' key '); * $b = Authcode ($a, ' DECODE ', ' key ');
$b (ABC) * * $a = authcode (' abc ', ' ENCODE ', ' key ', 3600); * $b = Authcode (' abc ', ' DECODE ', ' key '); 
Within one hours, $b (ABC), otherwise $b is null/public static function Authcode ($string, $operation = ' DECODE ', $key = ', $expiry = 3600) {
$ckey _length = 4;
With the secret key length value 0-32;
Join with the secret key, you can make ciphertext without any regularity, even if the original and key is identical, the encryption results will be different each time, increase the difficulty of cracking. The larger the value, the greater the ciphertext change law, the ciphertext change = 16 $ckey _length//When this value is 0 o'clock, the random key $key = MD5 ($key? $key: ' key ') is not generated; Here you can fill in the default key value
$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; $res Ult . = Chr (ord ($string [$i]) ^ ($box [($box [$a] + $box [$j])% 256]); } if ($operation = = ' DECODE ') {if (substr ($result, 0,) = 0 | | | substr ($result, 0)-time () > 0) &AMP;&A mp  substr ($result) = = substr (MD5 (substr ($result,). $keyb) (0)) {return substr ($result, 26);} else {return ';}}
else {return $KEYC. Str_replace (' = ', ', Base64_encode ($result));} public static function GbkToUtf8 ($STR) {return iconv ("GBK", "UTF-8", $str);}/** * Get all directories and files contained in the input directory * returned in associative array * author
: FLYNETCN */static Public Function Deepscandir ($dir) {$fileArr = array (); $dirArr = Array (); $dir = RTrim ($dir, '//'); if (Is_dir ($dir)) {$dirHandle = Opendir ($dir); while (false!== ($fileName = Readdir ($dirHandle)) {$subFile = $dir. Directory_separator.
$fileName; if (Is_file ($subFile)) {$FILEARR [] = $subFile;} elseif (Is_dir ($subFile) && str_replace ('. ', ', $fileName)!= ') {$DIRARR [] = $subFile; $arr = self::d eepscandir ($subFile); $diRarr = Array_merge ($DIRARR, $arr [' dir ']);
$FILEARR = Array_merge ($FILEARR, $arr [' file ']);
} closedir ($dirHandle);
Return Array (' dir ' => $dirArr, ' file ' => $fileArr); /** * Obtain all files contained in the input directory * AUTHOR:FLYNETCN/static public function Get_dir_files ($dir) {if (Is_file ($dir)) {R
Eturn Array ($dir);
} $files = Array (); if (Is_dir ($dir) && ($dir _p = Opendir ($dir)) {$ds = Directory_separator; while ($filename = Readdir ($dir _p))!= = False) {if ($filename = = '. ' | | $filename = = ' ... ')
{continue;}
$filetype = filetype ($dir. $ds. $filename); if ($filetype = = ' dir ') {$files = Array_merge ($files, Self::get_dir_files ($dir. $ds. $filename))} elseif ($filetype = = ' F
Ile ') {$files [] = $dir. $ds. $filename;}}
Closedir ($dir _p);
return $files;  }
}

It's a lot of 1000 lines. Can't save, view complete and download

Http://xiazai.jb51.net/201509/yuanma/Helper.rar

The above content is the entire description of this article, like a friend can download the source code OH directly.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.