Home > Backend Development > PHP Tutorial > Some classes and methods of ThinkPHP

Some classes and methods of ThinkPHP

巴扎黑
Release: 2016-11-22 16:13:42
Original
1288 people have browsed it

Thinkphp code

Get the client IP address

Get the client IP address

$type means return type 0 Return IP address 1 Return IPV4 address number

function get_client_ip($type = 0) {

​ $type = $type ? 1 : 0;

static $ip = NULL;

if ($ip !== NULL) return $ip[$type];

if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {R $ Arr = Explode (',', $ _Server ['http_x_Forwarded_For']);

$ POS = Array_Search ('UNKNOWN', $ Arr); ET ($ Arr [$ POS]);

$ ip = trim ($ arr [0]);

} elseif (isset ($ _ server ['http_client_ip']) {

$ ip = $ _Server ['http_client_ip'] ; ip2long($ ip);

$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);

return $ip[$type];

}

File byte size formatting

Byte formatting formats the byte number as the size described by B K M G T

function byte_format($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];

}

or

function get_size($s,$u='B',$p =1){

$us = array('B'=>'K','K'=>'M','M'=>'G','G'=>'T' );

return (($u!=='B')&&(!isset($us[$u]))||($s<1024))?(number_format($s,$p)." $u"):(get_size($s/1024,$us[$u],$p));

}

Display rainbow string

is used to display rainbow string, supports UTF8 and Chinese, the effect is as follows:

function color_txt($str){

$len = mb_strlen($str);

$colorTxt = '';

for($i=0; $i<$len; $i++ ) {

                  $colorTxt .= ''.mb_substr($str,$i,1,'utf-8').'';

}

return $colorTxt;

}

function rand_color(){

return '#'.sprintf("%02X",mt_rand(0,255)).sprintf("%02X", mt_rand(0,255)).sprintf("%02X",mt_rand(0,255));

}

Let PHP provide file downloads faster

Generally speaking, we can directly point the URL to a The file located under the Document Root guides users to download files.

 However, by doing this, there is no way to do some statistics, permission checks, etc. So, many times, we use PHP to do the forwarding. Provide users with file downloads.

 $file = "/tmp/dummy.tar.gz";

 header("Content-type: application/octet-stream");

 header(' Content-Disposition: attachment; filename="' . basename($file) . '"');

 header("Content-Length: ". filesize($file));

readfile($file);

But there is a problem with this, that is, if the file has a Chinese name, some users may download the file name with garbled characters.

So, let’s make some modifications (reference: :

$file = "/tmp/中文名.tar.gz";

 $filename = basename($file);

 header("Content-type: application/octet-stream");

   //Processing Chinese files Name

  $ua = $_SERVER["HTTP_USER_AGENT"];

  $encoded_filename = urlencode($filename);

  $encoded_filename = str_replace("+", "%20", $encoded_filename);

  if (preg_match ("/MSIE/", $ua)) {

 header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');

 } else if (preg_match("/Firefox/", $ua)) {

 header("Content-Disposition: attachment; filename*="utf8''" . $filename . '"');

  } else {

  header('Content-Disposition: attachment; filename="' . $filename . '"');

 }

 header('Content-Disposition: attachment; filename="' . $filename . '"');

 header("Content-Length: ". filesize($file));

 readfile($file);

Well, it looks much better now, but there is still a problem, that It is readfile. Although PHP's readfile tries to be as efficient as possible and does not occupy PHP's own memory, in fact it still needs to use MMAP (if supported), or a fixed buffer to loop through the file and output it directly.

 When outputting, if it is Apache + PHP mod, it needs to be sent to the output buffer of Apache. Finally, it is sent to the user. For Nginx + fpm, if they are deployed separately, it will also bring additional network IO .

So, can the Webserver directly send the file to the user without going through the PHP layer?

Today, I saw an interesting article: How I PHP: X-SendFile.

 We can use Apache’s module mod_xsendfile to let Apache send this file directly to the user:

 

 $file = "/tmp/中文名.tar.gz";

 $filename = basename($ file);

 header("Content-type: application/octet-stream");

  //Processing Chinese file names

  $ua = $_SERVER["HTTP_USER_AGENT"];

 $encoded_filename = urlencode($filename );

 $encoded_filename = str_replace("+", "%20", $encoded_filename);

 if (preg_match("/MSIE/", $ua)) {

 header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');

 } else if (preg_match("/Firefox/", $ua)) {

 header("Content-Disposition: attachment; filename*="utf8'' " . $filename . '"');

 } else {

 header('Content-Disposition: attachment; filename="' . $filename . '"');

 }

 header('Content-Disposition : attachment; filename="' . basename($file) . '"');

   // Let Xsendfile send the file

  header("X-Sendfile: $file");

X-Sendfile header will It is processed by Apache, and the response file is sent directly to the Client.

Lighttpd and Nginx also have similar modules. If you are interested, you can look for it

Configure the htaccess file to hide index.php

for Hide index.php in the URL address under the apache environment

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^( .*)$ index.php/$1 [QSA,PT,L]

Remove blanks and comments in PHP code

PHP has a built-in php_strip_whitespace method for reading php file and remove blanks and comments in the code, but it does not support directly reading the content to remove blanks and comments. The following method can support reading the string content, and the ThinkPHP framework has this method built in.

/**

* Remove blanks and comments in the code

* @param string $content code content

* @return string

*/

function strip_whitespace($content) {

$stripStr = '';

//Analyze php source code

$tokens = token_get_all($content);

$last_space = false;

for ($i = 0, $j = count($tokens); $i < $j; $i++) {

                                                                                               = false;

                                                                                                                                                                            

case T_COMMENT: D Case t_doc_comment:

Break;

// Filter Terrace

Case T_Whitespace:

if (! $ Last_space) {

$ stripstr. = '';

$ last_space = true;

                    break;

                case T_START_HEREDOC:

                    $stripStr .= "<<

                    break;

                case T_END_HEREDOC:

                    $stripStr .= "THINK;n";

                    for($k = $i+1; $k < $j; $k++) {

                        if(is_string($tokens[$k]) && $tokens[$k] == ';') {

                            $i = $k;

                            break;

                        } else if($tokens[$k][0] == T_CLOSE_TAG) {

                            break;

                        }

                    }

                    break;

                default:

                    $last_space = false;

                    $stripStr  .= $tokens[$i][1];

            }

        }

    }

    return $stripStr;

}

 

 

检查字符串是否是UTF8编码

用于判断某个字符串是否采用UTF8编码

function is_utf8($string){

    return preg_match('%^(?:

         [x09x0Ax0Dx20-x7E]            # ASCII

       | [xC2-xDF][x80-xBF]             # non-overlong 2-byte

       |  xE0[xA0-xBF][x80-xBF]        # excluding overlongs

       | [xE1-xECxEExEF][x80-xBF]{2}  # straight 3-byte

       |  xED[x80-x9F][x80-xBF]        # excluding surrogates

       |  xF0[x90-xBF][x80-xBF]{2}     # planes 1-3

       | [xF1-xF3][x80-xBF]{3}          # planes 4-15

       |  xF4[x80-x8F][x80-xBF]{2}     # plane 16

   )*$%xs', $string);

}

 

 

XSS安全过滤

来源于网络,用于对字符串进行XSS安全过滤。

function remove_xss($val) {

   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed

   // this prevents some character re-spacing such as

   // note that you have to handle splits with n, r, and t later since they *are* allowed in some inputs

   $val = preg_replace('/([x00-x08,x0b-x0c,x0e-x19])/', '', $val);

   // straight replacements, the user should never need these since they're normal characters

   // this prevents like

   $search = 'abcdefghijklmnopqrstuvwxyz';

   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

   $search .= '1234567890!@#$%^&*()';

   $search .= '~`";:?+/={}[]-_|'\';

   for ($i = 0; $i < strlen($search); $i++) {

      // ;? matches the ;, which is optional

      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

      // @ @ search for the hex values

      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;

      // @ @ 0{0,7} matches '0' zero to seven times

      $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;

   }

   // now the only remaining whitespace attacks are t, n, and r

   $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');

   $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');

   $ra = array_merge($ra1, $ra2);

   $found = true; // keep replacing as long as the previous round replaced something

   while ($found == true) {

      $val_before = $val;

      for ($i = 0; $i < sizeof($ra); $i++) {

         $pattern = '/';

         for ($j = 0; $j < strlen($ra[$i]); $j++) {

            if ($j > 0) {

               $pattern .= '(';

               $pattern .= '([xX]0{0,8}([9ab]);)';

               $pattern .= '|';

               $pattern .= '|(�{0,8}([9|10|13]);)';

               $pattern .= ')*';

            }

            $pattern .= $ra[$i][$j];

         }

         $pattern .= '/i';

         $replacement = substr($ra[$i], 0, 2).''.substr($ra[$i], 2); // add in <> to nerf the tag

         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags

         if ($val_before == $val) {

            // no replacements were made, so exit the loop

            $found = false;

         }

      }

   }

   return $val;

}

 

 

COOKIE用法示例

cookie方法是ThinkPHP内置的函数,用于完成cookie的设置、获取和删除操作。

设置

cookie('name','value');  //设置cookie

cookie('name','value',3600); // 指定cookie保存时间为1小时

 

高级设置

cookie('name','value',array('expire'=>3600,'prefix'=>'think_')); // 指定有效期和前缀

// 下面的代码和上面等效

cookie('name','value','expire=3600&prefix=think_')

 

获取

$value = cookie('name');

 

无论是否设置了前缀参数,cookie方法会自动判断。

删除

删除某个cookie值,可以用:

cookie('name',null);

 

If you need to clear cookies, you can use:

cookie(null); // Clear all cookie values ​​for the currently set prefix

cookie(null,'think_'); // Clear all cookie values ​​for the specified prefix

The verification code cannot be displayed? It is usually caused by the BOM information. This code can solve the problem of the verification code not being displayed. (Code to remove BOM information in batches)

Sometimes, we need to display the verification code in the local test environment There is no problem. Once deployed on the server, the verification code cannot be displayed where it needs to be displayed? If you also encounter the same problem, please read below.

Most of the causes of the problem are caused by BOM header information, usually thinkphp All configuration files must remove BOM header information. What is BOM header information? Baidu will tell you.

My usual solution is to create a new code file that removes BOM header information from all files after deploying it to the server. Then Just run it.

For example: I create a new delBom.php file in the server root directory. Just run http://www.xxx.com/delBom.php. The code is as follows:

if (isset($_GET['dir']){ //Set the file directory

$basedir=$_GET['dir'];

}else{

$basedir = '.';

}

$auto = 1;

checkdir($basedir);

function checkdir($basedir){

if ($dh = opendir($basedir)) {

while (($file = readdir($dh)) !== false) {

if ($file != '.' && $file != '..'){

if (!is_dir($basedir."/".$file)) {

echo "filename: $basedir/$file ".checkBOM("$basedir/$file")."
";

}else{

  $dirname = $basedir."/".$file;

checkdir($dirname);

}

}

}

closedir($dh);

}

}

function checkBOM ($filename) {

glo bal $auto;

$contents = file_get_contents ($filename);

$charset[1] = substr($contents, 0, 1);

$charset[2] = substr($contents, 1, 1);

$charset[3] = substr ($contents, 2, 1);

if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {

if ($auto == 1) {

$rest = substr($contents, 3);

rewrite ($filename, $rest);

return ("BOM found, automatically removed._http://www.k686.com");

} else {

return ("< ;font color=red>BOM found.");

}

}

else return ("BOM Not Found.");

}

function rewrite ($filename, $data) {

$filenum = fopen($filename, "w");

flock($filenum, LOCK_EX);

fwrite($filenum, $data);

fclose($filenum);

}

?>

U method usage examples, address method, can be used in models or templates

U method is a method used to automatically generate URL addresses in ThinkPHP, which can help you due to different environments and configurations The corresponding URL address is automatically generated.

Features are as follows:

1. Automatically identify the current URL pattern

2. Automatically identify the current PATH_INFO delimiter

3. Domain name and second-level domain name support

4. Pseudo-static and anchor point support

5. Routing address support

Therefore, when using the U method, you basically don’t need to pay attention to what URL mode and configuration parameters are currently used. You can just call it according to the unified rules of the U method. When actually generating the URL address, U The method is automatically recognized.

The following are some basic usages:

//The read operation address of the current module, the incoming parameter id is 5

U('read','id=5');

If you want to pass in a variable , then use:

U('read','id='.$vo['id']);

If your U method is called in a template, it generally needs to be written as:

Read article

Generate the index operation address of the Blog module and pass in more parameters:

U ('blog/index','cate_id=5&type=1');

Of course, you can also use array parameters:

U('blog/index',array('cate_id'=>5,' type'=>1));

If there are relatively few parameters, you can also pass them in directly in the first parameter:

U('Blog/read?id=5');

U(' Blog/cate?cate_id=1&status=1')

Support group generation:

U('Home/Blog/read?id=5'); // The read operation address of the blog module under the Home group

U('Admin/Blog/cate?cate_id=1&status=1'); // Admin Grouping

means

U method will automatically add the currently configured pseudo-static suffix. If you configure multiple pseudo-static suffixes, the first one will be added by default. If you need to specify a pseudo-static suffix, you can also use :

U('Blog/read','id=1','xml');

means outputting the pseudo-static URL address with .xml suffix

If you want to use the U method to output the routing address, You need to add "/" before the first parameter, for example:

U('/news/1');

means that the URL address to be generated is a routing address such as news/1.

If you need to generate a URL address with a domain name, you can use:

U('Blog/read@blog.thinkphp.cn','id=1');

or

U('Blog /read@blog','id=1');

represents the second-level blog domain name address of the current domain name.

Supports anchor point generation (note that you need to update the latest Git version to support it)

U('Blog/read#review','id=5');

The generated URL address will be included in the end #review anchor for easy jumping to the comments section.

Set the HTTP cache of the image, you can also set the JS and CSS

If it is an Apache environment, you can add the following code in the .htaccess file to set the HTTP cache and validity period of the image (needs to be turned on Apache's headers module supports), reducing the website's picture resource request pressure, improving access speed and your pagespeed value^_^.

Header set Cache-Control "max-age=604800"

The above code sets up a one-week HTTP cache for images on the website. Of course, you can also add http cache to js or css files.

Check if there are external links in the string

/**

* all_external_link Check whether the string contains external links

* @param string $text text

* @param string $host domain name

* @return boolean false if there is an external link true if there is no external link

*/

function all_external_link($text = '', $host = '') {

if (empty($host )) $host = $_SERVER['HTTP_HOST'];

$reg = '/http(?:s?)://((?:[A-za-z0-9-]+.)+[A -za-z]{2,4})/';

preg_match_all($reg, $text, $data);

$math = $data[1];

foreach ($math as $value) { A if ($ value! = $ Host) Return false;

}

return true; Add the following code to the file. When accessing abc.com, it will be redirected to www.abc.com. Of course, you can also set up redirection to other domain names.

RewriteEngine on

RewriteCond %{HTTP_HOST} ^abc.com$ [NC]

RewriteRule ^(.*)$ http://www.abc.com/$1 [R =301,L]

PHP gets the client’s IP, geographical information, browser information, local real IP

// Function to get the client’s IP, Geographic information, browser, local real IP

class get_gust_info {

////Get the visitor browser type

function GetBrowser(){

if(!empty($_SERVER['HTTP_USER_AGENT'])) {

$br = $_SERVER['HTTP_USER_AGENT'];

if (preg_match('/MSIE/i',$br)) {

$br = 'MSIE';

}else if (preg_match('/ Firefox/i',$br)) {

$br = 'Firefox';

}elseif (preg_match('/Chrome/i',$br)) {

$br = 'Chrome';

} elseif (preg_match('/Safari/i',$br)) {

$br = 'Safari';

}elseif (preg_match('/Opera/i',$br)) {

$br = ' Opera';

}else {

} } $br = 'Other';

}

return $br;

}else{return "Failed to obtain browser information!";}

}

/ ///Get the visitor browser language

function GetLang(){

if(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])){

$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

$lang = substr($lang,0,5);

if(preg_match("/zh-cn/i",$lang)){

$lang = "Simplified Chinese";

}elseif(preg_match ("/zh/i",$lang)){

  $lang = "Traditional Chinese";

  }else{

   $lang = "English";

  }

  return $lang;

 ​

}else{return "Failed to obtain browser language!";}

}

////Get the guest operating system

function GetOs(){

if(!empty($_SERVER['HTTP_USER_AGENT'] )){

$OS = $_SERVER['HTTP_USER_AGENT'];

if (preg_match('/win/i',$OS)) {

$OS = 'Windows';

}elseif (preg_match( '/mac/i',$OS)) {

$OS = 'MAC';

}elseif (preg_match('/linux/i',$OS)) {

$OS = 'Linux';

}elseif (preg_match('/unix/i',$OS)) {

  $OS = 'Unix';

  }elseif (preg_match('/bsd/i',$OS)) {

  $OS = 'BSD';

}else {

} $OS = 'Other';

}

                        return $OS;

////Get the visitor’s real ip

function Getip(){

if(!empty($_SERVER["HTTP_CLIENT_IP"])){

$ip = $_SERVER["HTTP_CLIENT_IP"];

}

if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ //Get proxy ip

$ips = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);

}

if($ ip){

$ips = array_unshift($ips,$ip);

}

$count = count($ips);

for($i=0;$i<$count;$i++ ){

if(!preg_match("/^(10|172.16|192.168)./i",$ips[$i])){//Exclude LAN ip

$ip = $ips[$i];

break;

}

}

$tip = empty($_SERVER['REMOTE_ADDR']) ? $ip : $_SERVER['REMOTE_ADDR'];

if($tip=="1 27.0.0.1" ;

function get_onlineip() {

$mip = file_get_contents("http://city.ip138.com/city0.asp");

if($mip){

preg_match("/[.*]/" ,$mip,$sip);

                                                                                                                                                                                                                                  $p = array("/[/",""/"); {return "Failed to obtain local IP! ";}

}

////Get the visitor's location name based on ip

function Getaddress($ip=''){

if(empty($ip)){

$ip = $this ->Getip();

}

$ipadd = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=".$ip);//According to Sina API interface acquisition

if($ipadd){

$charset = iconv("gbk","utf-8",$ipadd);

preg_match_all("/[x{4e00}-x{9fa5}]+ /u",$charset,$ipadds);

return $ipadds; //Return a two-dimensional array

}else{return "addree is none";}

}

}

$gifo = new get_gust_info();

echo "Your ip:".$gifo->Getip();

echo "
Location:";

$ipadds = $gifo->Getaddress( );

foreach($ipadds[0] as $value){

  echo "rn ".iconv("utf-8","gbk",$value); br/>Browser type: ".$gifo->GetBrowser();

echo "
Browser language:".$gifo->GetLang();

echo "
Operating system:".$gifo->GetOs();

?>

URL safe string base64 encoding and decoding

If you use the base64_encode and base64_decode methods directly, the generated string may not be suitable for URL addresses. The following method can solve this problem: URL safe string encoding:

function urlsafe_b64encode($string) {

$data = base64_encode($string);

$data = str_replace(array('+','/ ','='),array('-','_',''),$data);

return $data;

}

URL safe string decoding:

function urlsafe_b64decode( $string) {

$data = str_replace(array('-','_'),array('+','/'),$string);

$mod4 = strlen($data) % 4;

if ($mod4) {

$data .= substr('====', $mod4);

}

return base64_decode($data);

}

Get customers End browser information

/**

* Get the client browser type

* @param string $glue The connector between the browser type and version number

* @return string|array Passing the connector will connect the browser type and version number and return a string Otherwise, directly return the array false for unknown browser type

*/

function get_client_browser($glue = null) {

$browser = array();

$agent = $_SERVER['HTTP_USER_AGENT']; //Get Client information

/* Define browser feature regular expressions*/

$regex = array(

                                                                                                                         ' => '/(Chrome)/(d+.d+)/',

'firefox' => '/(Firefox)/(d+.d+)/',

'opera' => '/ (Opera)/(d+.d+)/',

'safari' => '/Version/(d+.d+.d) (Safari)/',

);

foreach($regex as $type => $reg) {

                                                                                                                use using                   use   through   through   use ’s ’     through out through out through out through out through out through out through out ’'' ‐ ‐ ‐‐ ‐ through ‐ ‐ preg_match($reg, $agent, $data); safari' ? array($data[2], $data[1]) : array($data[1], $data[2]);

                   break; ) ? false : (is_null($glue) ? $browser : implode($glue, $browser));

}

The timestamp friendly formatting function showed just, a few seconds ago

in some In the Weibo system, it is often necessary to display how long ago the time was compared to the current time, such as: just now, 5 seconds ago, 5 hours ago, 5 days ago... This kind of

/**

*

+-------------------------------------------------- --------------------------

* Description Friendly display time

+---------------- -------------------------------------------------- --

* @param int $time The timestamp to be formatted defaults to the current time

+-------------------------- ----------------------------------------

* @return string $text format The transformed timestamp

+------------------------------------------------ --------------------------

* @author yijianqing

+--------------- -------------------------------------------------- ---

* /

function mdate($time = NULL) {

$text = '';

$time = $time === NULL || $time > time() ? time() : intval($time) ;

$t = time() - $time; //Time difference (seconds)

if ($t == 0)

$text = 'just';

elseif ($t < 60)

$text = $t . 'Seconds ago'; // Within one minute

elseif ($t < 60 * 60)

$text = floor($t / 60) . 'Minutes ago'; //One hour Within

elseif ($t < 60 * 60 * 24)

$text = floor($t / (60 * 60)) . 'hours ago'; // Within one day

elseif ($t < 60 * 60 * 24 * 3)

$text = floor($time/(60*60*24)) ==1 ? 'Yesterday' . date('H:i', $time) : 'The day before yesterday' . date('H:i', $time) ; //Yesterday and the day before yesterday

elseif ($t < 60 * 60 * 24 *30)

                                                                                                                                    through //Within one year

else

                                                                                                                                         .

Using this function, we only need to use

{$vo.time|mdate}

to achieve time-friendly display in the foreground

to convert the returned data set into a tree structure

/**

* Convert the returned data set into a tree

* @param array $list Data set

* @param string $pk Primary key

* @param string $pid Parent node name

* @param string $child child Node name

* @param integer $root Root node ID

* @return array Converted tree

*/

function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root=0) {

$tree = array ();// Create a Tree

if(is_array($list)) {

// Create an array reference based on the primary key

$refer = array();

foreach ($list as $key => $ data) {

                                                                                                                                                            // Judgment Does parent exist? $parentId = $data[$pid];

if ($root == $parentId) {

}else{

                                                                                                                     $list[$key];

                                                                                                                                          

Avatar editing - when not changing the avatar

This is currently done and the judgment code snippet will be uploaded

/ * if(!$upload->upload()) {// Upload error message

$this->error($upload->getErrorMsg());

}else{// Obtained successfully Upload file information

$info = $upload->getUploadFileInfo();

} */

changed to:

$upload->upload();

$info = $upload-> getUploadFileInfo();

In this way, no error will be prompted even if the image is not uploaded, and then add

Make the following judgment in the update() method:

if(is_null($info[0]["savename"]) ){

$data['face']=$_POST['face'];

}else{

$data['face']=$info[0]["savename"];

}

Merge array function

When calling PHP’s native array_merge, if the first parameter is empty, the return result will be empty. This function handles it accordingly.

function MergeArray($list1,$list2)

{

if(!isEmpty($list1) && !isEmpty($list2))

{

return array_merge($list1,$list2);

}

else return (isEmpty($list1)?(isEmpty($list2)?null:$list2):$list1);

}

function isEmpty($data)

{

return null == $data || false == $data || "" == $data;

}

Google Translate plug-in call, use CURL to call

The interface to call Google Translate, curl support needs to be turned on.

/*

Google Translate Function by QQ366958903

$text Text to be translated

$tl Target language

$sl Original language

$ie Character encoding

*/

function translate($text='',$tl='zh-CN',$sl='auto',$ie='UTF-8'){

$ch = curl_init('http://translate.google.cn/');

curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS,"&hl=zh-CN&sl={$sl}&ie={$ie}&tl={$tl}&text=".urlencode($text));

$html = curl_exec($ch);

preg_match('#(.*?)

echo translate($text,'en');

?> sq'=>'Albanian',

'ar'=>'Arabic',

'az'=>'Azerbaijani ALPHA',

'ga'=>'Irish',

'et'=>'Estonian',

'be'=>'Belarusian',

'bg'=>'Bulgarian',

'is'=>'Icelandic ',

'pl'=>'Polish',

'fa'=>'Persian',

'af'=>'Boolean (Afrikaans)',

'da '=>'Danish',

'de'=>'German',

'ru'=>'Russian',

'fr'=>'French',

'tl' =>'Filipino',

'fi'=>'Finnish',

'ka'=>'Georgian ALPHA',

'ht'=>'Haitian Creole ALPHA',

'ko'=>'Korean',

'nl'=>'Dutch',

'gl'=>'Galician',

'ca'=> ;'Catalan',

'cs'=>'Czech',

'hr'=>'Croatian',

'lv'=>'Latvian',

'lt'=>'Lithuanian',

'ro'=>'Romanian',

'mt'=>'Maltese',

'ms'=>'Malay ',

'mk'=>'Macedonian',

'no'=>'Norwegian',

'pt'=>'Portuguese',

'ja'=>' Japanese',

'sv'=>'Swedish',

'sr'=>'Serbian',

'sk'=>'Slovak',

'sl'=> 'Slovenian',

'sw'=>'Swahili',

'th'=>'Thai',

'tr'=>'Turkish',

'cy '=>'Welsh',

'uk'=>'Ukrainian',

'eu'=>'Basque Spanish ALPHA',

'es'=>'Spanish ',

'iw'=>'Hebrew',

'el'=>'Greek',

'hu'=>'Hungarian',

'hy'=> ;'Armenian ALPHA',

'it'=>'Italian',

'yi'=>'Yiddish',

'hi'=>'Hindi',

'ur'=>'INDIUURDUALLPHA',

'id'=>'Indonesian',

'en'=>'English',

'vi'=>' Vietnamese',

'zh-TW'=>'Chinese (Traditional)',

'zh-CN'=>'Chinese (Simplified)',

Backup database, can back up the entire The library or backup partial table

is all written in the module. You can back up the entire library or select partial table backup

Correction of an error, line 361 empty was used incorrectly

class BaksqlAction Extends Communication {

Public $ config = ''; // Related configuration

public $ model = ''; // instantiated a model

public $ content; // content

public $ dbname = ';// /database name

  public $dir_sep = '/';                                        ​ parent::_initialize();

​ header("Content-type: text/html;charset= utf-8"); M');

          $this->config = array(

                                                          ’ ’ s ’ s     ‐ ‐ ‐ ‐ ‐ ‐ $this->config = array(

                                                                                     ('Db_backup'), where does the backup file exist

'iscompress' = & gt; 0, // Whether to turn on GZIP compression [Unbound]

'isdownload' = & gt; 0 // Whether to download the file after the backup is completed [ Not tested】

);

$this->dbName = C('DB_NAME'); t;model = new Model();

//$sql = ' set interactive_timeout=24*3600'; ; * +---- -------------------------------------------------- ------------------

* * @ Backed up data list

* +------------------- -------------------------------------------------- ---

                                                                                                                                                                                                             ($fileArr as $key => $value) {

                                                                                                                                                                                                                                           $path . '/' . $value)); <1024? number_Format ($ Filesize, 2). 'KB':

Number_Format ($ FILESIZE /1024, 2). 'MB';

// Construct a column table array

$ list [] = Array (

'name' = > $value,

                                                                     } }

      }

                                                                                                                                                                                                                                                                          } list);

                                                                                                                                                                                $this-> ----------------------------------------

* * @ Get data sheet

* +---------------------------------------- --------------------------------

*/

function tablist() {

         $list = $this->model->query("SHOW TABLE STATUS FROM {$this->dbName}"); //Get table information

                          //echo $Backup->getLastSql() ;

                                                                                    $this->assign('list', $list); -------------------------------------------------- -------------

* * @ Back up the entire database

* +------------------------- --------------------------------------------------

* /

function backall() {

$tables = $this->getTables();

if ($this->backup($tables)) {

$this->success('Database backup Success! ', '/public/ok');

                                                                                                                                   ​ * +- -------------------------------------------------- ---------------------

* * @ Backup by table, batch

* +------------- -------------------------------------------------- --------

                                                                                                                                      "​ ​ ​ $this->success('Database Backup successful! ');

                                                                                                                                                                                               $this->success(' ! ' ; ->success ('Data restoration is successful!', '/Public/ok'); Backup

function deletebak() {

if (unlink($this->config['path'] . $this->dir_sep . $_GET['file'])) {

$this-> success('Delete backup successfully!', '/public/ok');

                                                                                                                                                                                                                   Deletion

* +------------------------------------------------- --------------------------

* * @ Download backup file

* +------------ -------------------------------------------------- ----------

*/

function downloadBak() {

$file_name = $_GET['file'];

$file_dir = $this->config['path'] ;  $file = fopen($file_dir . "/" . $file_name, "r"); // Open the file

                                                                                                                                                                                                                                                                             . ");

header("Accept-Ranges: bytes");

header("Accept-Length: " . filesize($file_dir . "/" . $file_name));

            header('Content-Transfer-Encoding: binary');               header("Content-Disposition: attachment; filename=" . $file_name); : no-cache');                     header('Expires: 0'); fclose ($file);

                                                                                                         --------------------------------------------------

* * @ Get the array of files in the directory

* +---------------------------------------- --------------------------------

* * @ $FilePath Directory path

* * @ $Order Sort

* +------------------------------------------------- --------------------------

* * @ Get the file list in the specified directory and return an array

* +------ -------------------------------------------------- ----------------

*/

private function MyScandir($FilePath = './', $Order = 0) {

" $FilePath = opendir($FilePath) ;

                                                                                                                                                                                    ;

return $fileArr;

}

/* * ************************************** *************************************************** **** */

/* -

* * +----------------------------------- ----------------------------------------

* * @ Read backup file

* + -------------------------------------------------- -----------------------

* * @ $fileName File name

* +--------------- -------------------------------------------------- -------

*/

private function getFile($fileName) {

$this->content = '';

$fileName = $this->trimPath($this-> $ext == '.sql') {

                                          $this->content = file_get_contents($fileName);                                                                              de(' ', gzfile($fileName));

                                                              

            $this->error( 'File does not exist!');

                                                                                                                                                  ------------------------------------------------

* * @ Write data to disk

* +----------------------------------------- ----------------------------------

*/

private function setFile() {

$recognize = '' ;

                  $recognize = $this->dbName;

                                                use   with  $recognize             through   through   through   through out through out through out through out through through through over over over'''''‐‐‐'‐‐‐‐‐‐ dbName's . . date('YmdHis') . '_' . mt_rand(100000000, 999999999) . '.sql');

          $path = $this->setPath($fileName);

                                     True) {t $ This- & gt; ERROR ("" Can't create a backup directory directory '$ PATH' ");Le If (! File_put_contents ($ FILENAME, $ This-& GT; Content, Lock_ex)) {

$ This- & GT; Error ('' Writing file failure, please check disk space or permissions! ');

}

} } else {

                                                                                                                                                                                                           

                  gzwrite($gz , $ this->content); ');

          }

                                                                                                                                                                                                     ‐‐‐‐‐‐‐‐‐‐‐‐ this->config['isDownload']) {

                  $this -& gt; Downloadfile ($ FILENAME);

}}}

Private function trimpath ($ PATH) {

Return Str_replace (Array ('/', '// -,' \\ ') $tmp = '; 7 ))

                                               return $tmp;      ob_end_clean();

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header('Content-Description: File Transfer');

header('Content-Type: application/octet-stream');

header('Content-Length: ' . filesize($fileName));

header('Content-Disposition: attachment; filename=' . basename($fileName));

readfile($fileName);

}

/* -

* +----------------------------------------- ----------------------------------

* * @ Add ` `

to the string * +---- -------------------------------------------------- ------------------

* * @ $str string

* +------------------- -------------------------------------------------- ---

* * @ Return `$str`

* +---------------------------------- ---------------------------------------

*/

private function backquote($ str) {

                                                                                      . --------------------------------------------------

* * @ Get all tables of the database

* +---------------------------------------- ----------------------------------

* * @ $dbName Database name

* +-- -------------------------------------------------- --------------------

*/

private function getTables($dbName = '') {

if (!empty($dbName)) {

                  $sql = 'SHOW TABLES ';                                          t = $this->model->query($sql) ;

$info = array();

                                                                                                                                                                                                                   /* -

* +------------------------------------------------- -----------------------

* * @ Split the passed data into arrays according to the specified length

* +------- -------------------------------------------------- ---------------

* * @ $array The data to be divided

* * @ $byte The length to be divided

* +--------- -------------------------------------------------- -------------

* * @ Split the array according to the specified length and return the divided array

* +--------------- -------------------------------------------------- -------

*/

private function chunkArrayByte($array, $byte = 5120) {

$i = 0;

$sum = 0;

$return = array();

                                                                                                                                                                                                                                                                            $sum += strlen($v);

} Elseif ($ SUM == $ Byte) {

$ Return [++ $ i] [] [] = $ v;

$ SUM = 0;

} else {

$ Return [++ $ i] [ ] = $v;

                                                                                                             

}

/* -

 *  +--------- -------------------------------------------------- -------------

* * @ Backup data {Back up each table, view and data}

* * +---------------- -------------------------------------------------- ------

* * @ $tables The table array that needs to be backed up

* +---------------------------- --------------------------------------------------

*/

private function backup($tables) {

                                                                                                                                              through This file is created by MySQLReback ' . date('Y-m-d H:i:s') . ' */';

          foreach ($tables as $i => $table) {                     $table = $this-> ;backquote ($table);

                                                                                                                                                                                                                                                                                       ->content .= "rn DROP VIEW IF EXISTS {$table};/* MySQLReback Separation */ " . $tableRs[0]["Create View"] . ";/* MySQLReback Separation */";

            }

                                                                                                                                                                                                                                                              ->content .= "rn DROP TABLE IF EXISTS {$table};/* MySQLReback Separation */ " . $tableRs[0]["Create Table"] . ";/* MySQLReback Separation */";

                        $ tableDateRow = $this->model->query("SELECT * FROM {$table}");S if (FALSE! = $ Tabledaterow) {

Foreach ($ TableACH ($ TableDaterow as & $ Y) {

Foreach ($ y as & $ v) {

if ($ v == '') // Correcting empty as When 0, return tree

                                                                    else

                                                                                                                                             $v = "'" . mysql_escape_string($v) . "'"; Symbol

                                                                                                        }

                                                                                   ;

                                                                                   . /* MySQLReback Separation */';

if ($values ​​!= ';/* MySQLReback Separation */') {                                                                    >content . = "rn INSERT INTO {$table} VALUES {$values}";

                                                                                                                                                                    dump($this-> }

                                                                                                                                                                                   /* -

* * +-- -------------------------------------------------- ------------------

* * @ Restore data

* +------------------- -------------------------------------------------- ---

* * @ $fileName File name

* +---------------------------------- ----------------------------------------

*/

private function recover_file($fileName ) {

                                                                                                                                              through -& gt; content);

Foreach ($ Content as $ i = & gt; $ SQL) {

$ SQL = TRIM ($ SQL);

IF (! Empty ($ SQL)) {

$ MES = $this->model->execute($sql);                   $table_change = array('null' = > '''');

                                                                                                                 $sql = strtr($sql, $table_change);                                                                                                                                                                                            If an error is encountered, record the error

                                                                                                                             set_log($log_text);

                                                                                                                                   }

                                                                                                                                                                                                                                                                       ,,,,,,,,,, ?>

$this->_get(); Usage example automatic filtering

$this->_get('a','b','c');

Three parameters:

a, $ _GET variable name submitted;

b, filter function (multiple separated by commas, such as: 'trim' / 'trim, String');

c, default value;

A simple function that returns a specified error code and error page

httpstatus('404');

will send a 404 error to the client, and the error page can be customized.

Put the function in common.php, it will be loaded automatically and you can call it at will

/**

* Return the error code and place the error page under the entry file directory ./Public/httpstatus, named 404.html, 403.html, 503.html, etc.

* @param $string Error code

* @ param $msg error message such as NOT FOUND, can be omitted

*/

function httpstatus($string="404",$msg=""){

header ("http/1.1 {$string} {$msg}");

include './Public/httpstatus/'.$string.'.html';

exit;

}

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template