A detailed description of common php self-built functions in some php projects

Source: Internet
Author: User
This article provides a detailed analysis of common php self-built functions in some php projects, for more information, see the following php functions, which are the most commonly used project development functions in it power. these functions are used in many projects and are also common.
1. processing functions of the request interface

The code is as follows:


/**
* 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 posting data!
Curl_setopt ($ ch, CURLOPT_POST, 1 );
// Add the post variable
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

The code is as follows:


/**
* @ Get the file extension
* @ $ Pic string Image path
*/
Function get_file_ext ($ pic ){
Return substr ($ pic, strrpos ($ pic, '.') + 1 );
}


3. reversible encryption and decryption functions

The code is as follows:


/**
* String encryption
* @ Param $ string the characters to be encrypted
* @ Param $ operation encryption or decryption
* @ Param $ key: website 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 (1, 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 ));
}
}


4. convert string to hexadecimal

The code is as follows:


/**
* Convert string to hexadecimal
* @ 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 $ R. = ($ hexes [(ord ($ s {$ I})> 4)]. $ hexes [(ord ($ s {$ I}) & 0xf)]);
Return $ r;
}


5. hexadecimal conversion string

The code is as follows:


/**
* Hexadecimal conversion string
* @ Param unknown_type $ s
*/
Function hex2str ($ s ){
$ R = "";
For ($ I = 0; $ I {
$ 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. return the strings or arrays processed by addslashes.

The code is as follows:


/**
* Returns a string or array processed by addslashes.
* @ Param $ string the string or array 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. return strings or arrays processed by stripslashes

The code is as follows:


/**
* Returns the string or array processed by stripslashes.
* @ Param $ string the string or array 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.

The code is as follows:


/**
* Returns a string or array processed by htmlspecialchars.
* @ Param $ string the string or array 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 the request ip address

The code is as follows:


/**
* Obtain the request ip address
*
* @ 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. support for UTF8/GBK character truncation

The code is as follows:


/**
* UTF-8/GBK character truncation is supported.
* @ 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 ('region', '',' & ','" ', "'", ''', ','-',' <', '> ','·','... '), $ 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 ('hour', '&', '"'," '",'-',' <', '> ','·','... '), Array ('',' & ','" ', ''','-',' <','> ', '·','... '), $ Strcut );
} Else {
$ Dotlen = strlen ($ dot );
$ Maxi = $ length-$ dotlen-1;
$ Current_str = '';
$ Search_arr = array ('&', '', '"', "'",'-',' <','> ', '·','... ', 'Signature ');
$ 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

The code is as follows:


/**
* Generate random strings
*
* @ Param int $ length output length
* @ Param string $ chars (optional). The default value is 0123456789.
* @ Return string
*/
Function random ($ length, $ chars = '20140901 '){
$ Hash = '';
$ Max = strlen ($ chars)-1;
For ($ I = 0; $ I <$ length; $ I ++ ){
$ Hash. = $ chars [mt_rand (0, $ max)];
}
Return $ hash;
}


12. convert a string to an array

The code is as follows:


/**
* Convert a string to an array
*
* @ Param string $ data string
* @ Return array returns the array format. if data is null, an empty array is returned.
*/
Function string2array ($ data ){
If ($ data = '') return array ();
Eval ("\ $ array = $ data ;");
Return $ array;
}


13. convert the array to a string

The code is as follows:


/**
* Convert an array to a string
*
* @ Param array $ data array
* @ Param bool $ isformdata if it is 0, new_stripslashes is not used for processing. optional. the default value is 1.
* @ Return string returns a string. if data is null, null is returned.
*/
Function array2string ($ data, $ isformdata = 1 ){
If ($ data = '') return '';
If ($ isformdata) $ data = new_stripslashes ($ data );
Return addslashes (var_export ($ data, TRUE ));
}


14. number of bytes to be converted to another unit

The code is as follows:


/**
* The number of converted bytes is in other units.
*
*
* @ Param string $ filesize byte size
* @ Return string return size
*/
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;
}

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.