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
}
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
$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
= 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
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

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
