Common class libraries in PHP development

Source: Internet
Author: User
Tags foreach mail mixed rand sprintf strlen unique id


PHP Common Class Library

Array class


Class Libarray


{


/**


* Multidimensional Array merging


* @return Array


*/


public static function merge ()


{


$args = Func_get_args ();


$array = [];


foreach ($args as $arg) {


if (Is_array ($arg)) {


foreach ($arg as $k => $v) {


if (Is_array ($v)) {


$array [$k] = Isset ($array [$k])? $array [$k]: [];


$array [$k] = Self::merge ($array [$k], $v);


} else {


$array [$k] = $v;


}


}


}


}


return $array;


}

/**


* Multidimensional to one dimension


* [1=>[' a ' => ' v1 ']] to [' 1|a ' => ' v1 ']


* @param array $array


* @param string $delimiter


* @param string $key


* @return Array


*/


public static function MTo1 (array $array, $delimiter = ' | ', $key = ')


{


$data = [];


if (!is_array ($array)) {


return $data;


}


foreach ($array as $k => $v) {


$keyNew = Trim ($key. $delimiter. $k, $delimiter);


if (Is_array ($v)) {


$data = Array_merge ($data, Self::mto1 ($v, $delimiter, $keyNew));


} else {


$data [$keyNew] = $v;


}


}


return $data;


}

/**
* Array Sorting
* @param array $array
* @param $column
* @param bool $reverse
* @return BOOL
*/
public static function sort (array & $array, $column, $reverse = FALSE)
{
$arrColumn = [];
foreach ($array as $key => $val) {
$arrColumn [$key] = $val [$column];
}
Return Array_multisort ($arrColumn, $reverse? SORT_DESC:SORT_ASC, $array);
}

   /**
     * Add index
     * @param array $array
& nbsp;    * @param $key
     * @return Array
     */
& nbsp;   public static function index (array $array, $key)
    {
         $ret = [];
        foreach ($array as $val) {
      & nbsp;     $ret [$val [$key]] = $val;
       }
        return $ret;
   }

   /**
     * Add prefix
     * @param $array
 & nbsp;   * @param null $pre
     * @param null $suf
     * @retur N Array
     */
    public static function Addfix (array $array, $pre = NULL, $ Suf = NULL)
    {
        $ret = [];
   & nbsp;    foreach ($array as $key => $val) {
        & nbsp;   $ret [$key] = $pre. $val. $suf;
       }
        return $ret;
   }
}


Data checking class
Class Libcheck
{
/**
* is IP (IPv4)
* @param $ip
* @return BOOL
*/
public static function IsIP ($IP)
{
$isIP = Filter_var ($ip, filter_validate_ip)? True:false;
return $isIP;
}

/**
* Is the email address
* @param $mail
* @return BOOL
*/
public static function IsMail ($mail)
{
$isMail = Filter_var ($mail, filter_validate_email)? True:false;
return $isMail;
}

/**
* is a URL
* @param $url
* @return BOOL
*/
public static function Isurl ($url)
{
$isMail = Filter_var ($url, Filter_validate_url)? True:false;
return $isMail;
}

/**
* is a positive integer
* @param $num
* @return BOOL
*/
public static function Isposiint ($num)
{
$isPosiInt = Is_int ($num) && $num > 0;
return $isPosiInt;
}

   /**
     * is in scope
     * @param $num
 & nbsp;   * @param int $min
     * @param null $max
     * @return BOOL
     */
    public static function Isbetween ($num, $min = 0, $max = NULL
    {
        $isBetween = $num >= $min;
         if ($max) {
             $isBetween = $isBetween && $num <= $max;
       }
        return $isBetween;
   }

/**
* Whether it is a valid length
* @param $str
* @param int $min
* @param null $max
* @return BOOL
*/
public static function Isvalidlen ($str, $min = 1, $max = NULL)
{
$length = Mb_strlen ($STR);
$isValidLen = Self::isbetween ($length, $min, $max);
return $isValidLen;
}
}


File class

Class Libfile


{


/**


* Get all the files in the directory


* @param $path


* @return Array


*/


public static function GetFiles ($path)


{


$path = Self::formatepath ($path);


$dir = Opendir ($path);


$files = [];


while (($filename = Readdir ($dir))!== FALSE) {


if ($filename!= '. ' &amp;&amp; $filename!= ' ... ') {


$files [] = $path. $filename;


}


}


Closedir ($dir);


return $files;


}

   /**
     * In-mode directory files
     * @param $path
     * @param $pattern
     * @return Array
     */
    public static function Getfilesbypattern ($path, $pattern)
    {
 & nbsp;      $path = Self::formatepath ($path);
        $filePattern = sprintf ('%s%s ', $path, $pattern);
        return Glob ($filePattern);
   }

/**
* Get last modification time
* @param $path
* @return int
*/
public static function Getmodifiedtime ($path)
{
Return Filemtime ($path);
}

/**
* Format path
* @param $path
* @return String
*/
public static function Formatepath ($path)
{
return RTrim ($path, '/'). ' /';
}
}


HTTP class

Class Libhttp
{
Const TIMEOUT_DEFAULT = 30;
Private $_ch = NULL;

   /**
     * Get method
     * @param $url
 & nbsp;   * @param array $options
     * @return bool|mixed
      */
    public function Get ($url, $options = [])
    {
         return $this->_send ($url, NULL, NULL, $options);
   }

/**
* Post method
* @param $url
* @param array $params
* @param array $options
* @return bool|mixed
*/
Public Function post ($url, $params = [], $options = [])
{
return $this->_send ($url, ' POST ', $params, $options);
}

/**
* Error message
* @return String
*/
Public Function error ()
{
Return Curl_error ($this->_ch);
}

/**
* ERROR number
* @return int
*/
Public Function errno ()
{
Return Curl_errno ($this->_ch);
}

/**


* @param $url


* @param string $method


* @param array $params


* @param array $options


* @return bool|mixed


*/


Private Function _send ($url, $method = ' get ', $params = [], $options = [])


{


$this-&gt;_ch = Curl_init ($url);


curl_setopt ($this-&gt;_ch, Curlopt_returntransfer, TRUE);


curl_setopt ($this-&gt;_ch, Curlopt_connecttimeout, Self::timeout_default);


if ($method = = ' POST ') {


$options [Curlopt_post] = TRUE;


$options [Curlopt_postfields] = $params;


}


Curl_setopt_array ($this-&gt;_ch, $options);


$result = curl_exec ($this-&gt;_ch);


Return ($this-&gt;errno () = 0)? $result: FALSE;


}

/**
* __destruct
*/
Public Function __destruct ()
{
Curl_close ($this->_ch);
}
}


String class

Class Libstring


{


/**


* Random string


* @param int $length


* @param bool $num


* @param bool $lower


* @param bool $upper


* @return String


*/


public static function rand ($length =5, $num =true, $lower =true, $upper =true)


{


$str = ';


$num &amp;&amp; $str. = ' 0123456789 ';


$lowercase &amp;&amp; $str. = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ';


$uppercase &amp;&amp; $str. = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ';


$rand = substr (Str_shuffle ($STR),-$length);


return $rand;


}

/**
* String interception (single time)
* @param $ld
* @param $rd
* @param $str
* @return String
*/
public static function sub ($ld, $rd, $STR)
{
$start = Strpos ($str, $ld) + strlen ($LD);
$end = Strpos ($str, $rd, $start);
$data = substr ($str, $start, $end-$start);
return $data;
}

/**


* String interception (Batch)


* @param $ld


* @param $rd


* @param $str


* @return Array


*/


public static function Subs ($ld, $rd, $STR)


{


$data = [];


$lLen = strlen ($LD);


$rLen = strlen ($RD);


$offset = 0;


while (($start = Strpos ($str, $ld, $offset))!== FALSE) {


$start + + $lLen;


$end = Strpos ($str, $rd, $start);


$data [] = substr ($str, $start, $end-$start);


$offset = $end + $rLen;


}


return $data;


}

/**
* Generate Unique ID
* @return String
*/
public static function Uniqid ()
{
return MD5 (Uniqid (rand (), true);
}
}


Other tool classes

Class LibTool
{
/**
* Ip->int
* @param $ip
* @return String
*/
public static function Ip2long ($IP)
{
$long = sprintf ('%u ', Ip2long ($IP));
return $long;
}

/**
* System Load
* @return Mixed
*/
public static function Loadavg ()
{
$load = Sys_getloadavg () [0];
return $load;
}

/**
* Write log file
* @param $file
* @param $msg
* @param bool $newLine
*/
public static function log ($file, $msg, $newLine = TRUE)
{
$newLine && $msg. = "\ n";
File_put_contents ($file, $msg, file_append);
}

/**
* Amount of memory used
* @return Float
*/
public static function Memoryusage ()
{
$memery = Memory_get_usage ()/1024/1024;
return $memery;
}

/**


* Browser variable output


* @param $var


* @param bool| FALSE $return


* @param bool| TRUE $strict


* @return bool|mixed|string


*/


public static function Dump ($var, $return = FALSE, $strict = TRUE)


{


if (! $strict) {


if (Ini_get (' html_errors ')) {


$output = Print_r ($var, TRUE);


$output = sprintf (' &lt;pre&gt;%s&lt;/pre&gt; ', Htmlspecialchars ($output, ent_quotes));


} else {


$output = Print_r ($var, TRUE);


}


} else {


Ob_start ();


Var_dump ($var);


$output = Ob_get_clean ();


if (!extension_loaded (' Xdebug ')) {


$output = Preg_replace ('/\]\=\&gt;\n (\s+)/M ', '] =&gt; ', $output);


$output = sprintf (' &lt;pre&gt;%s&lt;/pre&gt; ', Htmlspecialchars ($output, ent_quotes));


}


}

if ($return) {
return $output;
} else {
Echo $output;
return TRUE;
}
}
}

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.