


Share a complete list of commonly used PHP tools in your own projects, share a complete list of PHP tools_PHP Tutorial
Jul 12, 2016 am 08:54 AMShare a complete list of commonly used PHP tools in your own projects, share a complete list of PHP tools
Php code
- /**
- * Helper class
- * @author www.shouce.ren
- *
- */
- class Helper
- {
- /**
- * Determine the current server system
- * @return string
- */
- public static function getOS(){
- if(PATH_SEPARATOR == ':'){
- ?????????return?'Linux';?
- }else{
- ?return 'Windows';
- } ?
- ?}?
- /**
- * Current microsecond number
- * @return number
- */
- public static function microtime_float() {
- list ( $usec, $sec ) = explode ( " ", microtime () );
- return (( float ) $usec ( float ) $sec);
- }??
- ????/**
- * Cut a string in utf-8 format (one Chinese character or character occupies one byte)
- *
- * @author zhao jinhan
- * @version v1.0.0
- *
- */??
- ????public?static?function?truncate_utf8_string($string,?$length,?$etc?=?'...')?{??
- ????????$result?=?'';??
- ????????$string?=?html_entity_decode?(?trim?(?strip_tags?(?$string?)?),?ENT_QUOTES,?'UTF-8'?);??
- ????????$strlen?=?strlen?(?$string?);??
- ????????for($i?=?0;?(($i?$strlen)?&&?($length?>?0));?$i? )?{??
- ????????????if?($number?=?strpos?(?str_pad?(?decbin?(?ord?(?substr?(?$string,?$i,?1?)?)?),?8,?'0',?STR_PAD_LEFT?),?'0'?))?{??
- ????????????????if?($length?
- ????????????????????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 folders
- * @param string $dir
- * @param boolean $all true means 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;??
- ????}
- /**?
- ?????*?郵件發(fā)送?
- ?????*?@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' );
- //Email configuration
- $mailer->SetLanguage('zh_cn');
- $mailer->Host = Yii::app()->params['emailHost']; //Sending mail server
- $mailer->Port = Yii::app()->params['emailPort']; //Mail port
- $mailer->Timeout = Yii::app()->params['emailTimeout'];//Email sending 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’s email address
- $mailer->FromName = Yii::app()->params['emailFormName']; // Sender’s name
- $mailer->AddReplyTo ( $mailer->Username );
- $mailer->CharSet = 'UTF-8';
- ?//Add email log?
- $modelMail = new MailLog ();
- $modelMail->accept = $toemail;
- $modelMail->subject = $subject;
- $modelMail->message = $message;
- ????????$modelMail->send_status?=?'waiting';??
- ????????$modelMail->save?();??
- ????????//?發(fā)送郵件??
- ????????$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 (emptyempty($str)) return $default;
- $preg = array(
- ???????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????????????????????????????????conditions), this range actually includes Traditional Chinese characters
- ); if ($default == 'gb2312') {
- ???????????????????????????????????????????????????????????????????????????????????????????? } ?else { ? ??????????????????????????????????????????????????????????????????????????????????????????? } ?
- if (!preg_match($preg[$default], $str)) {
- ????????return?$option;?
- } ?
- $str = @iconv($default, $option, $str);
- //Cannot be converted to $option, indicating that the original one is not $default if (
- empty empty(
- $str)) { ????????return?$option;?
- } ?
- return $default; }??
- ????/**
- * UTF-8 and gb2312 automatic conversion
- * @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)?{??
- ????????????????//?第一個字節(jié)判斷通過??
- ????????????????$char?=?$string?{ ?$i};??
- ????????????????if?((ord?(?$char?)?&?128)?==?128)?{??
- ????????????????????//?第二個字節(jié)判斷通過??
- ????????????????????$char?=?$string?{ ?$i};??
- ????????????????????if?((ord?(?$char?)?&?128)?==?128)?{??
- ????????????????????????$encoding?=?"UTF-8";??
- ????????????????????????break;??
- ????????????????????}??
- ????????????????}??
- ????????????}??
- ????????????if?((ord?(?$string?{$i}) & 192) == 192) {
- ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??????????$char = $string {
- $i}; ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
- ?????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????????????????????????? } ?
- if (strtoupper ( $encoding) == strtoupper (
- $outEncoding))
- ???????????return? $string;?
- ?
- else?
- ?return @iconv ($encoding, $outEncoding, $string);? ?}?
- /**
- * Returns all values ??of a key name in the 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 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;??
- ????}??
- ????/**
- * 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, radio button automatic selection
- *
- * @param $string Input characters
- * @param $param Conditions
- * @param $type 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 remote images
- * @param string $url The absolute url of the image
- * @param string $filepath The full path of the file (such as /www/images/test). This function will automatically determine the suffix name of the image based on the image URL and http header information
- * @param string $filename The name of the file to be saved (excluding extension)
- * @return mixed Returns an array describing the image information if the download is successful, false if the download fails
- */
- static public function downloadImage($url, $filepath, $filename) {
- //Header information returned by the server
- $responseHeaders = array();
- ?//Original picture name
- $originalfilename = '';
- //The suffix name of the picture
- $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 Http content
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- //Set the page after crawling jump (http 301, 302)
- 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 relevant information about this crawl
- $httpinfo = curl_getinfo($ch);
- curl_close($ch);
- if ($html !== false) {
- ?????????????????????????????????????????????????????????????????????????????????????????????????????? // Separate the header and body of the response. Since the server may use 302 jumps, the string needs to be separated into 2 substrings with the number of jumps ?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????>
- ?//The penultimate paragraph is the http header of the server’s last response
- ?$header = $httpArr[count($httpArr) - 2];
- ?//The penultimate paragraph is the content of the server’s last response
- ?$body = $httpArr[count($httpArr) - 1];
- ???????$header.="rn";?
- ?//Get the header information of the last response
- preg_match_all('/([a-z0-9-_] ):s*([^rn] )rn/i', $header, $matches);
- ?if (!emptyempty($matches) && count($matches) == 3 && !emptyempty( $matches[1]) && !emptyempty($matches[1])) {
- ??????????for ($i = 0; $i count($matches[1]); $i ) {?
- ??????????????if (array_key_exists($i, $matches[2])) {?
- ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? $responseHeaders[$matches[1][$i]] = $matches[2][$i]; > ????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????????????????????????????????????
- ?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ?
- if (0 '{(?:[^/\\] ).(jpg|jpeg|gif|png|bmp)$}i',
- $url , $matches)) {
- ????????????$originalfilename = $matches[0]; ????????????$ext = $matches[1];
- } ?else { ?
- ???????????if (array_key_exists('Content-Type', $responseHeaders)) {?
- ???????????????????????????????????????????????????????????????????????????????????????????????i', $responseHeaders['Content-Type'], $extmatches)) {
- ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????????????????????????? ? //Save the file
- ? if (!
- empty empty(
- $ext)) {
- ????????????????//If the directory does not exist, you must create the directory first ???????????if(!is_dir( $filepath)){?
- ??????????????????mkdir($filepath, 0777, true); ????????????????????????????????????????????????????????????????????????????????????????????????? ??????????
- $filepath .= '/'.$filename.".$ext";?
- ????????????$local_file = fopen($filepath, 'w');?
- ??????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? fclose($local_file); ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????, 'height' =>
- $sizeinfo[1], 'orginalfilename' => >$filepath, PATHINFO_BASENAME)); ????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????????????????????????????????????
- } ? ?return false; }??
- ????/**
- * Find if the IP is in a certain rank
- * @param string $ip The IP to be queried
- * @param $arrIP Banned 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;?//禁止所有??
- ????????????????break;??
- ????????????}??
- ????????????$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]?==?'*')){??
- ????????????????????//第三段為*?或者相同??
- ????????????????????if(($arr_cur_ip[3]?==?$tmp_arr[3])?||?($tmp_arr[3]?==?'*')){??
- ????????????????????????//第四段為*?或者相同??
- ????????????????????????$access?=?false;?//在禁止ip列,則禁止訪問??
- ????????????????????????break;??
- ????????????????????}??
- ????????????????}
- ??????????????????????????????????????????????????????????????????????????????????????????????? } ?
- return $access; ?}?
- /**
- * @param string $string Original text or cipher text
- * @param string $operation operation (ENCODE | DECODE), the default is DECODE
- * @param string $key key
- * @param int $expiry Ciphertext validity period, valid when encrypted, unit seconds, 0 means permanent validity
- * @return string The processed original text or the cipher text processed by base64_encode
- *
- * @example
- *
- * $a = authcode('abc', 'ENCODE', 'key');
- * $b = authcode($a, 'DECODE', 'key'); // $b(abc)
- *
- * $a = authcode('abc', 'ENCODE', 'key', 3600);

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach
