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').' span>';
}
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