FAQs about common PHP Tools in your project

Source: Internet
Author: User
Tags preg
: This article describes how to share common PHP Tools in your project. if you are interested in PHP tutorials, refer to it.
 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 exceeds Time $ 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 Mail logs $ ModelMail = new MailLog (); $ modelMail-> 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'; $ modelM Ail-> 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-\ x7 F] +/"," ", $ str); if (empty ($ str) return $ default; $ preg = array ("gb2312" => "/^ ([\ 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 <strl En ($ string); $ I ++) {if (ord ($ string {$ I}) <128) continue; if (ord ($ string {$ I }) & 224) = 224) {// The first byte is determined by $ char = $ string {++ $ I}; if (ord ($ char) & 128) = 128) {// The second byte is determined 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; else return @ 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;}/*** determine whether the file/directory can be written (replace the 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;}/*** formatting 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];}/*** drop-down box, the single-choice button automatically selects the ** @ param $ string input character * @ param $ param condition * @ param $ type * selected checked * @ return st Ring */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 $ orig Inalfilename = ''; // 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); // sets the capture jump (http 301,302) page after 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 */pu Blic 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; // 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 paragraph is * Or the same if ($ arr_cur_ip [3] = $ tmp_arr [3]) | ($ tmp_arr [3] = '*')) {// The fourth section is * or the same $ access = false; // in the forbidden ip 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', 'encode', 'key', 3600); * $ B = authcode ('ABC', 'Decode ', 'key'); // within an hour, $ 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; // add a random key, so that the ciphertext does not have any regularity, even if the original text and key are identical, the encryption results are different each time, increasing 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 );}}

More than 1000 lines of code it too much to save and can not send, view and download the complete tool class please go to the http://www.shouce.ren/post/view/id/1700

The above describes the common PHP tool categories in your project, including the content, and hope to be helpful to friends who are interested in PHP tutorials.

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.