PHP common tools and tools _ PHP tutorials

Source: Internet
Author: User
Tags preg
PHP Tools and tools. PHP Tools and tools? Php *** helper class ** @ authorwww. shouce. ren ** classHelper {*** determines the current server system * @ returnstring * publicstaticfunctionge PHP common tools, tools
 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 ;} /*** Traverse folder * @ param string $ dir * @ param boolean $ all true indicates recursive traversal * @ return array */public static 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 ;} /*** send an email ** @ 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']; // sending email server $ mailer-> Port = Yii: app ()-> params ['emailport']; // email Port $ mailer-> Timeout = Yii: app ()-> params ['emailtimeout']; // email sending Timeout value $ mailer-> ContentType =' Text/html '; // Set the 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 email address $ mailer-> FromName = Yii: app ()-> params ['emailformname']; // sender name $ mailer-> AddReplyTo ($ mailer-> Username); $ mailer-> CharSet = 'utf-8 '; // add email logs $ modelMail = new MailLog (); $ modelMai L-> accept = $ toemail; $ modelMail-> subject = $ subject; $ modelMail-> message = $ message; $ modelMail-> send_status = 'waiting '; $ modelMail-> save (); // send an email $ 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 ;}} /*** determine whether 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 ("g B2312 "=>"/^ ([\ xA1-\ xF7] [\ xA0-\ xFE]) + $ /", // check whether the regular expression is gb2312 "UTF-8" => "/^ [\ x {4E00}-\ x {9FA5}] + $/u ", // check whether the regular expression is a Chinese character (the UTF-8 encoding condition). The range actually 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 ); // It cannot be converted to $ option, indicating that the original $ default if (empty ($ str) {return $ option;} return $ default ;} /*** UTF-8 and gb2312 are automatically converted * @ 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 ($ strin G); $ I ++) {if (ord ($ string {$ I}) <128) continue; if (ord ($ string {$ I}) & 224) = 224) {// The first byte is judged by $ char = $ string {++ $ I}; if (ord ($ char) & 128) = 128) {// The 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) {// The second byte is determined by $ encoding = "GB2312"; break ;}} if (strtoupper ($ encoding) == strtoupper ($ outEncoding) return $ string; elsereturn @ iconv ($ encoding, $ outEncoding, $ string );} /*** return 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;}/*** determines whether the file/directory can be written (replacing the system Built-in is_writeable function) * @ param string $ 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 f Unction 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];}/*** drop-down box, the single-choice button automatically selects the ** @ param $ string input character * @ param $ param condition * @ param $ 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 the remote image ** @ param string $ the absolute url of the url image * @ param string $ full path of the filepath file (for example,/www/images/test ), this function automatically determines the image suffix * @ param string $ filename (excluding the extension) based on the image url and http header information) * @ return mixed: an array describing image information is returned after the download is successful. if the download fails, false */static public function downloadImage ($ url, $ filepath, $ filename) is returned) {// header information returned by the server $ responseHeaders = array (); // original image name $ originalfilename = ''; // Image suffix $ ext =''; $ ch = curl_init ($ url); // set the value returned by curl_exec to include the Http header curl_setopt ($ ch, CURLOPT_HEADER, 1); // set the value returned by curl_exec to include the Http content curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); // set the page curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, 1); // set the maximum number of HTTP redirection curl_setopt ($ ch, CURLOPT_MAXREDIRS, 3); // the data returned by the server (including http header information and content) $ html = curl_exec ($ ch); // obtain information about the capture. $ httpinfo = curl_getinfo ($ ch); curl_close ($ Ch); if ($ html! = False) {// separate the header and body of the response. because the server may use 302 redirection, therefore, the string must be separated into two + jump times substrings $ httpArr = explode ("\ r \ n", $ html, 2 + $ httpinfo ['redirect _ count']); // The second penultimate is the http header of the server's last response $ header = $ httpArr [count ($ httpArr) -2]; // The last line is the server's last response content $ body = $ httpArr [count ($ httpArr)-1]; $ header. = "\ r \ n"; // Get the header information of 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] ;}} // Obtain the image suffix 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 the object if (! Empty ($ ext) {// if the directory does not exist, create the 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 ;} /*** check whether the ip address is in a field * @ param string $ ip the ip address to be queried * @ param $ ip address prohibited by arrIP * @ return boolean */public static func Tion 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; // disable all breaks;} $ tmp_arr = explode ('. ', $ value); if ($ arr_cur_ip [0] = $ tmp_arr [0]) & ($ arr_cur_ip [1] = $ tmp_arr [1]) {// if ($ arr_cur_ip [2] = $ tmp_arr [2]) | ($ tmp_arr [2] = '*')) {// The third section is * or the same if ($ arr_cur_ip [3] = $ Tmp_arr [3]) | ($ tmp_arr [3] = '*') {// The fourth segment is * or the same $ access = false; // in the ip prohibited column, access to break is prohibited; }}} return $ access ;} /*** @ param string $ string original text or ciphertext * @ param string $ operation (ENCODE | DECODE ), the default value is DECODE * @ param string $ key * @ param int $ expiry. the ciphertext validity period is valid during encryption, in seconds, 0 is permanently valid * @ return string the original text after processing or the ciphertext after base64_encode processing ** @ example ** $ a = authcode ('ABC', 'encoding ', 'key'); * $ B = authcode ($ a, 'Decode ', 'Key'); // $ B (abc) ** $ a = authcode ('ABC', 'encoding', 'key', 3600 ); * $ B = authcode ('ABC', 'Decode', 'key'); // within an hour, $ B (abc ), otherwise, $ B is blank */public static function authcode ($ string, $ operation = 'Decode', $ key = '', $ expiry = 3600) {$ ckey_length = 4; // the length of the random key is 0-32. // adding a random key can make the ciphertext uncertain. even if the original text and the key are identical, the encryption result will be different each time, increase the difficulty of cracking. // The larger the value, the larger the ciphertext change law. The ciphertext changes to the power of $ ckey_length = 16 // when this value is 0, no random key $ key = md5 ($ key? $ Key: 'key'); // you can enter the default key value $ keya = md5 (substr ($ key, 0, 16) here )); $ 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 <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);} public static function gbkToUtf8 ($ str) {return iconv (" GBK "," UTF-8 ", $ str);}/*** get all directories and files contained in the input directory * return * author: flynetcn */static public function deepScanDir ($ dir) in the form of an associated array) {$ 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: deepScanDir ($ subFile); $ dirArr = array_merge ($ dirArr, $ arr ['dir']); $ fileArr = array_merge ($ fileArr, $ arr ['file']);} closedir ($ dirHandle );} return array ('dir' => $ dirArr, 'file' => $ fileArr );} /*** retrieve all files contained in the input directory * returns the * author: flynetcn */static public function get_dir_files ($ dir) {if (is_file ($ dir) in array format )) {return 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 = 'file') {$ files [] = $ dir. $ ds. $ filename ;}} closedir ($ dir_p);} return $ files ;}}

Too many lines can't be saved. view and download them completely.

: Http://www.shouce.ren/post/d/id/1700

Why? Php/*** helper class * @ author www. shouce. ren **/class Helper {/*** determines the current server system * @ return string */public static function ge...

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.