PHP common tools in their own projects to share

Source: Internet
Author: User
Tags ord preg yii
  0));  $i + +) {if ($number = Strpos (Str_pad (Decbin) (Ord (substr ($string, $i, 1)), 8, ' 0 ', str_pad_left),                ' 0 ') {if ($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; }/** * Traversal folder * @param string $dir * @param boolean $all true means recursive traversal * @return Array */public s             tatic function Scanfdir ($dir = ", $all = False, & $ret = Array ()) {if (false!== ($handle = Opendir ($dir))) { while (false!== ($file = Readdir ($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 {$ret [' files '] [] = $cur _path;        }}} closedir ($handle);    } return $ret; /** * Mail Send * @param string $toemail * @param string $subject * @param string $message * @return b Oolean */public static function SendMail ($toemail = ", $subject =", $message = ") {$mailer = Yii::crea        Tecomponent (' Application.extensions.mailer.EMailer ');        Mail configuration $mailer->setlanguage (' zh_cn '); $mailer->host = Yii::app ()->params[' emailhost ']; Outgoing 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 mailbox $mailer->fromname = Yii::app ()->params[' emailformname '];        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 = ' failed ';            $modelMail->error = $error;            $modelMail->save ();        return false; }}/** * To determine if the string is Utf-8 or gb2312 * @param unknown $STR * @param string $default * @return String * /public static function utf8_gb2312 ($str, $default = ' gb2312 ') {$str = Preg_replace ("/[\x01-\x7f]+/", "", $        STR);        if (empty ($STR)) return $default; $preg = Array ("gb2312" = "/^ ([\xa1-\xf7][\xa0-\xfe]) +$/",//Regular judgment is gb2312 "utf-8" = "/^[\x"        {4e00}-\x{9fa5}]+$/u ",//regular judgment whether it is a Chinese character (UTF8 encoding condition), this range has actually included the traditional Chinese characters); if ($default = = ' gb2312 ') {$option = ' utf-8';        } else {$option = ' gb2312 ';        } if (!preg_match ($preg [$default], $str)) {return $option;        } $str = @iconv ($default, $option, $STR);        Cannot be turned into $option, stating that the original is not $default if (empty ($STR)) {return $option;    } return $default;      }/** * Utf-8 and gb2312 Auto convert * @param unknown $string * @param string $outEncoding * @return unknown|string        */public static function Safeencoding ($string, $outEncoding = ' UTF-8 ') {$encoding = "UTF-8";            for ($i = 0; $i < strlen ($string); $i + +) {if (ord ($string {$i}) <) continue; if ((Ord ($string {$i}) & 224) = = 224) {//The first byte is judged by $char = $string {+ + $i                };                    if (Ord ($char) & 128) = = 128) {//second byte is judged by $char = $string {+ + $i};    if ((Ord ($char) & 128) = = 128) {                    $encoding = "UTF-8";                    Break                }}} if ((Ord ($string {$i}) & 192) = = 192) {//The first byte is judged by                $char = $string {+ + $i};                    if (Ord ($char) & 128) = = 128) {//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 STA        Tic function Array_key_values ($array =array (), $key = ") {$ret = array ();        foreach (array) $array as $k + = $v) {$ret [$k] = $v [$key];    } return $ret; }/** * Determine if the file/directory is writable (replacing 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; }/** * Formatted unit */static Public function Byteformat ($size, $dec = 2) {$a = array ("B", "KB", "MB        "," GB "," TB "," PB ");        $pos = 0;            while ($size >= 1024x768) {$size/= 1024;        $pos + +; } return Round ($size, $dec). " " .    $a [$pos];  }/** * drop-down box, radio button Automatically select * * @param $string input characters * @param $param conditions * @param $type Type * Selected Checked * @return String */static Public function selected ($string, $param = 1, $type = ' s        Elect ') {$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 the absolute URL of a string $url picture * @param the full path of a string $filepath file (for example,/www/images/test), this function will automatically root     According to the image URL and HTTP header information to determine the name of the image suffix * @param string $filename The file name to save (without extension) * @return mixed download successfully returns an array that describes the picture information, the download fails to return false */static Public function Downloadimage ($url, $filepath, $filename) {//The header information returned by the server $responseHeaders = arr        Ay ();        Original picture name $originalfilename = ';        The suffix name of the picture $ext = ';        $ch = Curl_init ($url); The value returned by setting Curl_exec contains the HTTP header curl_setopt ($ch, CURlopt_header, 1);        The value returned by setting Curl_exec contains the HTTP content curl_setopt ($ch, Curlopt_returntransfer, 1);        Set the crawl 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);        Data returned by the server (including HTTP header information and content) $html = curl_exec ($ch);        Get information about this crawl $httpinfo = Curl_getinfo ($ch);        Curl_close ($ch); if ($html!== false) {//Detach response header and body, because the server may use 302 jump, it is necessary to separate the string into the number of a.            Explode ("\r\n\r\n", $html, 2 + $httpinfo [' redirect_count ']);            The penultimate paragraph is the HTTP header of the server's last response $header = $HTTPARR [Count ($HTTPARR)-2];            The penultimate paragraph is the last time the server response content $body = $HTTPARR [Count ($HTTPARR)-1];            $header. = "\ r \ n";            Get 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]] = $MATC                    hes[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. = '/'. $filename. ".                $ext ";                $local _file = fopen ($filepath, ' w '); if (false!== $local _file) {if (False!== fwrite ($local _file, $body)) {fclose (                        $local _file);                        $sizeinfo = getimagesize ($filepath); 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 in a field * @param string $IP IP to query * @param $arrIP Forbidden IP * @return Boolean */        public static function ipaccess ($ip = ' 0.0.0.0 ', $arrIP = Array ()) {$access = true;        $ip && $arr _cur_ip = Explode ('. ', $IP); foreach (array) $arrIP as $key + = $value) {if ($value = = ' *.*.*.* ') {$access = false;            Prohibit all break;            } $tmp _arr = Explode ('. ', $value); if (($arr _cur_ip[0] = = $tmp _arr[0]) && ($arr _cur_ip[1] = = $tmp _arr[1])) {//The first two paragraphs are the same if ( ($arr _cur_ip[2] = = $tmp _arr[2]) | | ($tmp _arr[2] = = ' * ')) {//The 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;//disable access to break when the IP column is forbidden;    }}}} return $access; }/** * @param string $string original text or ciphertext * @param string $operation operation (ENCODE | DECODE), default is DECODE * @param string $key key * @param int $expiry ciphertext expiration, encryption time valid, unit seconds, 0 is permanent active * @return string     The processed text or ciphertext after base64_encode processing * * @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 empty */public static function Authcode ($string, $operation = ' DECODE ', $key = ', $expiry =        3600) {$ckey _length = 4;        Random key length value 0-32;        Join with the secret key, you can make ciphertext no rules, even if the original and key exactly the same, the encryption results will be different each time, increase the difficulty of cracking. The greater the value, the greater the ciphertext variation, the ciphertext change = 16 $ckey _length//When this value is 0 o'clock, the random key is not generated $key = MD5 ($key? $key: ' key ');        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 <, $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, ten) = = 0 | | substr ($result, 0,)-time    () > 0) && substr ($result, ten, +) = = substr (MD5 (substr ($result,) $keyb), 0, 16)) {            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); }    }

More than 1000 lines of code It's too much to save. To view and download the complete tool class, please go to http://www.shouce.ren/post/view/id/1700

The above describes the PHP common tools in their own projects to share, including the content, I hope the PHP tutorial interested in a friend to help.

  • Related Article

    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.