纪录了PHP的一些常用函数和函数代码!不要错过了哦。 PHP的一些常用函数 PHP String 函数 PHP Math 函数 PHP Error 和 Logging 函数 PHP Array 函数 PHP Array 函数 |
这下面是一些常用的函数实例哦。以后大家一定能用的上!(本文将不断更新,同时也希望热心的网友朋友们能贡献自己一点一滴的知识,大家共同进步,一起学习)
1、截取UTF-8编码下字符串的函数
1 /**
2 * 截取UTF-8编码下字符串的函数
3 *
4 * @param string $str 被截取的字符串
5 * @param int $length 截取的长度
6 * @param bool $append 是否附加省略号
7 *
8 * @return string
9 */
10 function sub_str($str, $length = 0, $append = true)
11 {
12 $str = trim($str);//去掉前后的空格
13 $strlength = strlen($str);
14
15 if ($length == 0 || $length >= $strlength)
16 {
17 return $str;
18 }
19 elseif ($length < 0)
20 {
21 $length = $strlength + $length;
22 if ($length < 0)
23 {
24 $length = $strlength;
25 }
26 }
27
28 if (function_exists('mb_substr'))
29 {
30 $newstr = mb_substr($str, 0, $length, EC_CHARSET);
31 }
32 elseif (function_exists('iconv_substr'))
33 {
34 $newstr = iconv_substr($str, 0, $length, EC_CHARSET);
35 }
36 else
37 {
38 //$newstr = trim_right(substr($str, 0, $length));
39 $newstr = substr($str, 0, $length);
40 }
41
42 if ($append && $str != $newstr)
43 {
44 $newstr .= '...';
45 }
46
47 return $newstr;
48 }
2、获得用户的真实IP地址
1 /**
2 * 获得用户的真实IP地址
3 *
4 * @access public
5 * @return string
6 */
7 function real_ip()
8 {
9 static $realip = NULL;
10
11 if ($realip !== NULL)
12 {
13 return $realip;
14 }
15
16 if (isset($_SERVER))
17 {
18 if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
19 {
20 $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
21
22 /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
23 foreach ($arr AS $ip)
24 {
25 $ip = trim($ip);
26
27 if ($ip != 'unknown')
28 {
29 $realip = $ip;
30
31 break;
32 }
33 }
34 }
35 elseif (isset($_SERVER['HTTP_CLIENT_IP']))
36 {
37 $realip = $_SERVER['HTTP_CLIENT_IP'];
38 }
39 else
40 {
41 if (isset($_SERVER['REMOTE_ADDR']))
42 {
43 $realip = $_SERVER['REMOTE_ADDR'];
44 }
45 else
46 {
47 $realip = '0.0.0.0';
48 }
49 }
50 }
51 else
52 {
53 if (getenv('HTTP_X_FORWARDED_FOR'))
54 {
55 $realip = getenv('HTTP_X_FORWARDED_FOR');
56 }
57 elseif (getenv('HTTP_CLIENT_IP'))
58 {
59 $realip = getenv('HTTP_CLIENT_IP');
60 }
61 else
62 {
63 $realip = getenv('REMOTE_ADDR');
64 }
65 }
66
67 preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
68 $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
69
70 return $realip;
71 }
3、计算字符串的长度(汉字按照两个字符计算)
1 /**
2 * 计算字符串的长度(汉字按照两个字符计算)
3 *
4 * @param string $str 字符串
5 *
6 * @return int
7 */
8 function str_len($str)
9 {
10 $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));
11
12 if ($length)
13 {
14 return strlen($str) - $length + intval($length / 3) * 2;
15 }
16 else
17 {
18 return strlen($str);
19 }
20 }
4、获得用户操作系统的换行符
1 /**
2 * 获得用户操作系统的换行符
3 *
4 * @access public
5 * @return string
6 */
7 function get_crlf()
8 {
9 /* LF (Line Feed, 0x0A, \N) 和 CR(Carriage Return, 0x0D, \R) */
10 if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win'))
11 {
12 $the_crlf = '\r\n';
13 }
14 elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac'))
15 {
16 $the_crlf = '\r'; // for old MAC OS
17 }
18 else
19 {
20 $the_crlf = '\n';
21 }
22
23 return $the_crlf;
24 }
5、邮件发送
1 /**
2 * 邮件发送
3 *
4 * @param: $name[string] 接收人姓名
5 * @param: $email[string] 接收人邮件地址
6 * @param: $subject[string] 邮件标题
7 * @param: $content[string] 邮件内容
8 * @param: $type[int] 0 普通邮件, 1 HTML邮件
9 * @param: $notification[bool] true 要求回执, false 不用回执
10 *
11 * @return boolean
12 */
13 function send_mail($name, $email, $subject, $content, $type = 0, $notification=false)
14 {
15 /* 如果邮件编码不是EC_CHARSET,创建字符集转换对象,转换编码 */
16 if ($GLOBALS['_CFG']['mail_charset'] != EC_CHARSET)
17 {
18 $name = ecs_iconv(EC_CHARSET, $GLOBALS['_CFG']['mail_charset'], $name);
19 $subject = ecs_iconv(EC_CHARSET, $GLOBALS['_CFG']['mail_charset'], $subject);
20 $content = ecs_iconv(EC_CHARSET, $GLOBALS['_CFG']['mail_charset'], $content);
21 $shop_name = ecs_iconv(EC_CHARSET, $GLOBALS['_CFG']['mail_charset'], $GLOBALS['_CFG']['shop_name']);
22 }
23 $charset = $GLOBALS['_CFG']['mail_charset'];
24 /**
25 * 使用mail函数发送邮件
26 */
27 if ($GLOBALS['_CFG']['mail_service'] == 0 && function_exists('mail'))
28 {
29 /* 邮件的头部信息 */
30 $content_type = ($type == 0) ? 'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;
31 $headers = array();
32 $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
33 $headers[] = $content_type . '; format=flowed';
34 if ($notification)
35 {
36 $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
37 }
38
39 $res = @mail($email, '=?' . $charset . '?B?' . base64_encode($subject) . '?=', $content, implode("\r\n", $headers));
40
41 if (!$res)
42 {
43 $GLOBALS['err'] ->add($GLOBALS['_LANG']['sendemail_false']);
44
45 return false;
46 }
47 else
48 {
49 return true;
50 }
51 }
52 /**
53 * 使用smtp服务发送邮件
54 */
55 else
56 {
57 /* 邮件的头部信息 */
58 $content_type = ($type == 0) ?
59 'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset;
60 $content = base64_encode($content);
61
62 $headers = array();
63 $headers[] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000';
64 $headers[] = 'To: "' . '=?' . $charset . '?B?' . base64_encode($name) . '?=' . '" <' . $email. '>';
65 $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
66 $headers[] = 'Subject: ' . '=?' . $charset . '?B?' . base64_encode($subject) . '?=';
67 $headers[] = $content_type . '; format=flowed';
68 $headers[] = 'Content-Transfer-Encoding: base64';
69 $headers[] = 'Content-Disposition: inline';
70 if ($notification)
71 {
72 $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
73 }
74
75 /* 获得邮件服务器的参数设置 */
76 $params['host'] = $GLOBALS['_CFG']['smtp_host'];
77 $params['port'] = $GLOBALS['_CFG']['smtp_port'];
78 $params['user'] = $GLOBALS['_CFG']['smtp_user'];
79 $params['pass'] = $GLOBALS['_CFG']['smtp_pass'];
80
81 if (empty($params['host']) || empty($params['port']))
82 {
83 // 如果没有设置主机和端口直接返回 false
84 $GLOBALS['err'] ->add($GLOBALS['_LANG']['smtp_setting_error']);
85
86 return false;
87 }
88 else
89 {
90 // 发送邮件
91 if (!function_exists('fsockopen'))
92 {
93 //如果fsockopen被禁用,直接返回
94 $GLOBALS['err']->add($GLOBALS['_LANG']['disabled_fsockopen']);
95
96 return false;
97 }
98
99 include_once(ROOT_PATH . 'includes/cls_smtp.php');
100 static $smtp;
101
102 $send_params['recipients'] = $email;
103 $send_params['headers'] = $headers;
104 $send_params['from'] = $GLOBALS['_CFG']['smtp_mail'];
105 $send_params['body'] = $content;
106
107 if (!isset($smtp))
108 {
109 $smtp = new smtp($params);
110 }
111
112 if ($smtp->connect() && $smtp->send($send_params))
113 {
114 return true;
115 }
116 else
117 {
118 $err_msg = $smtp->error_msg();
119 if (empty($err_msg))
120 {
121 $GLOBALS['err']->add('Unknown Error');
122 }
123 else
124 {
125 if (strpos($err_msg, 'Failed to connect to server') !== false)
126 {
127 $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['smtp_connect_failure'], $params['host'] . ':' . $params['port']));
128 }
129 else if (strpos($err_msg, 'AUTH command failed') !== false)
130 {
131 $GLOBALS['err']->add($GLOBALS['_LANG']['smtp_login_failure']);
132 }
133 elseif (strpos($err_msg, 'bad sequence of commands') !== false)
134 {
135 $GLOBALS['err']->add($GLOBALS['_LANG']['smtp_refuse']);
136 }
137 else
138 {
139 $GLOBALS['err']->add($err_msg);
140 }
141 }
142
143 return false;
144 }
145 }
146 }
147 }
6、获得服务器上的 GD 版本
1 /**
2 * 获得服务器上的 GD 版本
3 *
4 * @access public
5 * @return int 可能的值为0,1,2
6 */
7 function gd_version()
8 {
9 include_once(ROOT_PATH . 'includes/cls_image.php');
10
11 return cls_image::gd_version();
12 }
13
14 if (!function_exists('file_get_contents'))
15 {
16 /**
17 * 如果系统不存在file_get_contents函数则声明该函数
18 *
19 * @access public
20 * @param string $file
21 * @return mix
22 */
23 function file_get_contents($file)
24 {
25 if (($fp = @fopen($file, 'rb')) === false)
26 {
27 return false;
28 }
29 else
30 {
31 $fsize = @filesize($file);
32 if ($fsize)
33 {
34 $contents = fread($fp, $fsize);
35 }
36 else
37 {
38 $contents = '';
39 }
40 fclose($fp);
41
42 return $contents;
43 }
44 }
45 }
46
47 if (!function_exists('file_put_contents'))
48 {
49 define('FILE_APPEND', 'FILE_APPEND');
50
51 /**
52 * 如果系统不存在file_put_contents函数则声明该函数
53 *
54 * @access public
55 * @param string $file
56 * @param mix $data
57 * @return int
58 */
59 function file_put_contents($file, $data, $flags = '')
60 {
61 $contents = (is_array($data)) ? implode('', $data) : $data;
62
63 if ($flags == 'FILE_APPEND')
64 {
65 $mode = 'ab+';
66 }
67 else
68 {
69 $mode = 'wb';
70 }
71
72 if (($fp = @fopen($file, $mode)) === false)
73 {
74 return false;
75 }
76 else
77 {
78 $bytes = fwrite($fp, $contents);
79 fclose($fp);
80
81 return $bytes;
82 }
83 }
84 }
85
86 if (!function_exists('floatval'))
87 {
88 /**
89 * 如果系统不存在 floatval 函数则声明该函数
90 *
91 * @access public
92 * @param mix $n
93 * @return float
94 */
95 function floatval($n)
96 {
97 return (float) $n;
98 }
99 }
7、文件或目录权限检查函数
1 /**
2 * 文件或目录权限检查函数
3 *
4 * @access public
5 * @param string $file_path 文件路径
6 * @param bool $rename_prv 是否在检查修改权限时检查执行rename()函数的权限
7 *
8 * @return int 返回值的取值范围为{0 <= x <= 15},每个值表示的含义可由四位二进制数组合推出。
9 * 返回值在二进制计数法中,四位由高到低分别代表
10 * 可执行rename()函数权限、可对文件追加内容权限、可写入文件权限、可读取文件权限。
11 */
12 function file_mode_info($file_path)
13 {
14 /* 如果不存在,则不可读、不可写、不可改 */
15 if (!file_exists($file_path))
16 {
17 return false;
18 }
19
20 $mark = 0;
21
22 if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
23 {
24 /* 测试文件 */
25 $test_file = $file_path . '/cf_test.txt';
26
27 /* 如果是目录 */
28 if (is_dir($file_path))
29 {
30 /* 检查目录是否可读 */
31 $dir = @opendir($file_path);
32 if ($dir === false)
33 {
34 return $mark; //如果目录打开失败,直接返回目录不可修改、不可写、不可读
35 }
36 if (@readdir($dir) !== false)
37 {
38 $mark ^= 1; //目录可读 001,目录不可读 000
39 }
40 @closedir($dir);
41
42 /* 检查目录是否可写 */
43 $fp = @fopen($test_file, 'wb');
44 if ($fp === false)
45 {
46 return $mark; //如果目录中的文件创建失败,返回不可写。
47 }
48 if (@fwrite($fp, 'directory access testing.') !== false)
49 {
50 $mark ^= 2; //目录可写可读011,目录可写不可读 010
51 }
52 @fclose($fp);
53
54 @unlink($test_file);
55
56 /* 检查目录是否可修改 */
57 $fp = @fopen($test_file, 'ab+');
58 if ($fp === false)
59 {
60 return $mark;
61 }
62 if (@fwrite($fp, "modify test.\r\n") !== false)
63 {
64 $mark ^= 4;
65 }
66 @fclose($fp);
67
68 /* 检查目录下是否有执行rename()函数的权限 */
69 if (@rename($test_file, $test_file) !== false)
70 {
71 $mark ^= 8;
72 }
73 @unlink($test_file);
74 }
75 /* 如果是文件 */
76 elseif (is_file($file_path))
77 {
78 /* 以读方式打开 */
79 $fp = @fopen($file_path, 'rb');
80 if ($fp)
81 {
82 $mark ^= 1; //可读 001
83 }
84 @fclose($fp);
85
86 /* 试着修改文件 */
87 $fp = @fopen($file_path, 'ab+');
88 if ($fp && @fwrite($fp, '') !== false)
89 {
90 $mark ^= 6; //可修改可写可读 111,不可修改可写可读011...
91 }
92 @fclose($fp);
93
94 /* 检查目录下是否有执行rename()函数的权限 */
95 if (@rename($test_file, $test_file) !== false)
96 {
97 $mark ^= 8;
98 }
99 }
100 }
101 else
102 {
103 if (@is_readable($file_path))
104 {
105 $mark ^= 1;
106 }
107
108 if (@is_writable($file_path))
109 {
110 $mark ^= 14;
111 }
112 }
113
114 return $mark;
115 }
116
117 function log_write($arg, $file = '', $line = '')
118 {
119 if ((DEBUG_MODE & 4) != 4)
120 {
121 return;
122 }
123
124 $str = "\r\n-- ". date('Y-m-d H:i:s'). " --------------------------------------------------------------\r\n";
125 $str .= "FILE: $file\r\nLINE: $line\r\n";
126
127 if (is_array($arg))
128 {
129 $str .= '$arg = array(';
130 foreach ($arg AS $val)
131 {
132 foreach ($val AS $key => $list)
133 {
134 $str .= "'$key' => '$list'\r\n";
135 }
136 }
137 $str .= ")\r\n";
138 }
139 else
140 {
141 $str .= $arg;
142 }
143
144 file_put_contents(ROOT_PATH . DATA_DIR . '/log.txt', $str);
145 }
8、检查目标文件夹是否存在,如果不存在则自动创建该目录
1 /**
2 * 检查目标文件夹是否存在,如果不存在则自动创建该目录
3 *
4 * @access public
5 * @param string folder 目录路径。不能使用相对于网站根目录的URL
6 *
7 * @return bool
8 */
9 function make_dir($folder)
10 {
11 $reval = false;
12
13 if (!file_exists($folder))
14 {
15 /* 如果目录不存在则尝试创建该目录 */
16 @umask(0);
17
18 /* 将目录路径拆分成数组 */
19 preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
20
21 /* 如果第一个字符为/则当作物理路径处理 */
22 $base = ($atmp[0][0] == '/') ? '/' : '';
23
24 /* 遍历包含路径信息的数组 */
25 foreach ($atmp[1] AS $val)
26 {
27 if ('' != $val)
28 {
29 $base .= $val;
30
31 if ('..' == $val || '.' == $val)
32 {
33 /* 如果目录为.或者..则直接补/继续下一个循环 */
34 $base .= '/';
35
36 continue;
37 }
38 }
39 else
40 {
41 continue;
42 }
43
44 $base .= '/';
45
46 if (!file_exists($base))
47 {
48 /* 尝试创建目录,如果创建失败则继续循环 */
49 if (@mkdir(rtrim($base, '/'), 0777))
50 {
51 @chmod($base, 0777);
52 $reval = true;
53 }
54 }
55 }
56 }
57 else
58 {
59 /* 路径已经存在。返回该路径是不是一个目录 */
60 $reval = is_dir($folder);
61 }
62
63 clearstatcache();
64
65 return $reval;
66 }
9、获得系统是否启用了 gzip
1 /**
2 * 获得系统是否启用了 gzip
3 *
4 * @access public
5 *
6 * @return boolean
7 */
8 function gzip_enabled()
9 {
10 static $enabled_gzip = NULL;
11
12 if ($enabled_gzip === NULL)
13 {
14 $enabled_gzip = ($GLOBALS['_CFG']['enable_gzip'] && function_exists('ob_gzhandler'));
15 }
16
17 return $enabled_gzip;
18 }
10、递归方式的对变量中的特殊字符进行转义
1 /**
2 * 递归方式的对变量中的特殊字符进行转义
3 *
4 * @access public
5 * @param mix $value
6 *
7 * @return mix
8 */
9 function addslashes_deep($value)
10 {
11 if (empty($value))
12 {
13 return $value;
14 }
15 else
16 {
17 return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
18 }
19 }
11、将对象成员变量或者数组的特殊字符进行转
1 /**
2 * 将对象成员变量或者数组的特殊字符进行转义
3 *
4 * @access public
5 * @param mix $obj 对象或者数组
6 * @author Xuan Yan
7 *
8 * @return mix 对象或者数组
9 */
10 function addslashes_deep_obj($obj)
11 {
12 if (is_object($obj) == true)
13 {
14 foreach ($obj AS $key => $val)
15 {
16 $obj->$key = addslashes_deep($val);
17 }
18 }
19 else
20 {
21 $obj = addslashes_deep($obj);
22 }
23
24 return $obj;
25 }
12、递归方式的对变量中的特殊字符去除转义
1 /**
2 * 递归方式的对变量中的特殊字符去除转义
3 *
4 * @access public
5 * @param mix $value
6 *
7 * @return mix
8 */
9 function stripslashes_deep($value)
10 {
11 if (empty($value))
12 {
13 return $value;
14 }
15 else
16 {
17 return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
18 }
19 }
13、将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
1 /**
2 * 将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
3 *
4 * @access public
5 * @param string $str 待转换字串
6 *
7 * @return string $str 处理后字串
8 */
9 function make_semiangle($str)
10 {
11 $arr = array('0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
12 '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
13 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
14 'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
15 'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
16 'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
17 'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
18 'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
19 'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
20 'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
21 'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
22 't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
23 'y' => 'y', 'z' => 'z',
24 '(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[',
25 '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
26 '‘' => '[', '’' => ']', '{' => '{', '}' => '}', '《' => '<',
27 '》' => '>',
28 '%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-',
29 ':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.',
30 ';' => ',', '?' => '?', '!' => '!', '…' => '-', '‖' => '|',
31 '”' => '"', '’' => '`', '‘' => '`', '|' => '|', '〃' => '"',
32 ' ' => ' ');
33
34 return strtr($str, $arr);
35 }
14、 过滤用户输入的基本数据,防止script攻击
1 /**
2 * 过滤用户输入的基本数据,防止script攻击
3 *
4 * @access public
5 * @return string
6 */
7 function compile_str($str)
8 {
9 $arr = array('<' => '<', '>' => '>');
10
11 return strtr($str, $arr);
12 }
15、检查文件类型
1 /**
2 * 检查文件类型
3 *
4 * @access public
5 * @param string filename 文件名
6 * @param string realname 真实文件名
7 * @param string limit_ext_types 允许的文件类型
8 * @return string
9 */
10 function check_file_type($filename, $realname = '', $limit_ext_types = '')
11 {
12 if ($realname)
13 {
14 $extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
15 }
16 else
17 {
18 $extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
19 }
20
21 if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false)
22 {
23 return '';
24 }
25
26 $str = $format = '';
27
28 $file = @fopen($filename, 'rb');
29 if ($file)
30 {
31 $str = @fread($file, 0x400); // 读取前 1024 个字节
32 @fclose($file);
33 }
34 else
35 {
36 if (stristr($filename, ROOT_PATH) === false)
37 {
38 if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' ||
39 $extname == 'xls' || $extname == 'txt' || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' ||
40 $extname == 'pdf' || $extname == 'rm' || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' ||
41 $extname == 'swf' || $extname == 'chm' || $extname == 'sql' || $extname == 'cert'|| $extname == 'pptx' ||
42 $extname == 'xlsx' || $extname == 'docx')
43 {
44 $format = $extname;
45 }
46 }
47 else
48 {
49 return '';
50 }
51 }
52
53 if ($format == '' && strlen($str) >= 2 )
54 {
55 if (substr($str, 0, 4) == 'MThd' && $extname != 'txt')
56 {
57 $format = 'mid';
58 }
59 elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav')
60 {
61 $format = 'wav';
62 }
63 elseif (substr($str ,0, 3) == "\xFF\xD8\xFF")
64 {
65 $format = 'jpg';
66 }
67 elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt')
68 {
69 $format = 'gif';
70 }
71 elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
72 {
73 $format = 'png';
74 }
75 elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt')
76 {
77 $format = 'bmp';
78 }
79 elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt')
80 {
81 $format = 'swf';
82 }
83 elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0")
84 { // D0CF11E == DOCFILE == Microsoft Office Document
85 if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc')
86 {
87 $format = 'doc';
88 }
89 elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls')
90 {
91 $format = 'xls';
92 } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt')
93 {
94 $format = 'ppt';
95 }
96 } elseif (substr($str ,0, 4) == "PK\x03\x04")
97 {
98 if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'docx')
99 {
100 $format = 'docx';
101 }
102 elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xlsx')
103 {
104 $format = 'xlsx';
105 } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'pptx')
106 {
107 $format = 'pptx';
108 }else
109 {
110 $format = 'zip';
111 }
112 } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt')
113 {
114 $format = 'rar';
115 } elseif (substr($str ,0, 4) == "\x25PDF")
116 {
117 $format = 'pdf';
118 } elseif (substr($str ,0, 3) == "\x30\x82\x0A")
119 {
120 $format = 'cert';
121 } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt')
122 {
123 $format = 'chm';
124 } elseif (substr($str ,0, 4) == "\x2ERMF")
125 {
126 $format = 'rm';
127 } elseif ($extname == 'sql')
128 {
129 $format = 'sql';
130 } elseif ($extname == 'txt')
131 {
132 $format = 'txt';
133 }
134 }
135
136 if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false)
137 {
138 $format = '';
139 }
140
141 return $format;
142 }
16、对 MYSQL LIKE 的内容进行转义
1 /**
2 * 对 MYSQL LIKE 的内容进行转义
3 *
4 * @access public
5 * @param string string 内容
6 * @return string
7 */
8 function mysql_like_quote($str)
9 {
10 return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%', "\'" => "\\\\\'"));
11 }
17、获取服务器的ip
1 /**
2 * 获取服务器的ip
3 *
4 * @access public
5 *
6 * @return string
7 **/
8 function real_server_ip()
9 {
10 static $serverip = NULL;
11
12 if ($serverip !== NULL)
13 {
14 return $serverip;
15 }
16
17 if (isset($_SERVER))
18 {
19 if (isset($_SERVER['SERVER_ADDR']))
20 {
21 $serverip = $_SERVER['SERVER_ADDR'];
22 }
23 else
24 {
25 $serverip = '0.0.0.0';
26 }
27 }
28 else
29 {
30 $serverip = getenv('SERVER_ADDR');
31 }
32
33 return $serverip;
34 }
18、自定义 header 函数,用于过滤可能出现的安全隐患
1 /**
2 * 自定义 header 函数,用于过滤可能出现的安全隐患
3 *
4 * @param string string 内容
5 *
6 * @return void
7 **/
8 function ecs_header($string, $replace = true, $http_response_code = 0)
9 {
10 if (strpos($string, '../upgrade/index.php') === 0)
11 {
12 echo '<script type="text/javascript">window.location.href="' . $string . '";</script>';
13 }
14 $string = str_replace(array("\r", "\n"), array('', ''), $string);
15
16 if (preg_match('/^\s*location:/is', $string))
17 {
18 @header($string . "\n", $replace);
19
20 exit();
21 }
22
23 if (empty($http_response_code) || PHP_VERSION < '4.3')
24 {
25 @header($string, $replace);
26 }
27 else
28 {
29 @header($string, $replace, $http_response_code);
30 }
31 }
32
33 function ecs_iconv($source_lang, $target_lang, $source_string = '')
34 {
35 static $chs = NULL;
36
37 /* 如果字符串为空或者字符串不需要转换,直接返回 */
38 if ($source_lang == $target_lang || $source_string == '' || preg_match("/[\x80-\xFF]+/", $source_string) == 0)
39 {
40 return $source_string;
41 }
42
43 if ($chs === NULL)
44 {
45 require_once(ROOT_PATH . 'includes/cls_iconv.php');
46 $chs = new Chinese(ROOT_PATH);
47 }
48
49 return $chs->Convert($source_lang, $target_lang, $source_string);
50 }
51
52 function ecs_geoip($ip)
53 {
54 static $fp = NULL, $offset = array(), $index = NULL;
55
56 $ip = gethostbyname($ip);
57 $ipdot = explode('.', $ip);
58 $ip = pack('N', ip2long($ip));
59
60 $ipdot[0] = (int)$ipdot[0];
61 $ipdot[1] = (int)$ipdot[1];
62 if ($ipdot[0] == 10 || $ipdot[0] == 127 || ($ipdot[0] == 192 && $ipdot[1] == 168) || ($ipdot[0] == 172 && ($ipdot[1] >= 16 && $ipdot[1] <= 31)))
63 {
64 return 'LAN';
65 }
66
67 if ($fp === NULL)
68 {
69 $fp = fopen(ROOT_PATH . 'includes/codetable/ipdata.dat', 'rb');
70 if ($fp === false)
71 {
72 return 'Invalid IP data file';
73 }
74 $offset = unpack('Nlen', fread($fp, 4));
75 if ($offset['len'] < 4)
76 {
77 return 'Invalid IP data file';
78 }
79 $index = fread($fp, $offset['len'] - 4);
80 }
81
82 $length = $offset['len'] - 1028;
83 $start = unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);
84 for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8)
85 {
86 if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip)
87 {
88 $index_offset = unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0");
89 $index_length = unpack('Clen', $index{$start + 7});
90 break;
91 }
92 }
93
94 fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
95 $area = fread($fp, $index_length['len']);
96
97 fclose($fp);
98 $fp = NULL;
99
100 return $area;
101 }
19、去除字符串右侧可能出现的乱码
1 /**
2 * 去除字符串右侧可能出现的乱码
3 *
4 * @param string $str 字符串
5 *
6 * @return string
7 */
8 function trim_right($str)
9 {
10 $len = strlen($str);
11 /* 为空或单个字符直接返回 */
12 if ($len == 0 || ord($str{$len-1}) < 127)
13 {
14 return $str;
15 }
16 /* 有前导字符的直接把前导字符去掉 */
17 if (ord($str{$len-1}) >= 192)
18 {
19 return substr($str, 0, $len-1);
20 }
21 /* 有非独立的字符,先把非独立字符去掉,再验证非独立的字符是不是一个完整的字,不是连原来前导字符也截取掉 */
22 $r_len = strlen(rtrim($str, "\x80..\xBF"));
23 if ($r_len == 0 || ord($str{$r_len-1}) < 127)
24 {
25 return sub_str($str, 0, $r_len);
26 }
27
28 $as_num = ord(~$str{$r_len -1});
29 if ($as_num > (1<<(6 + $r_len - $len)))
30 {
31 return $str;
32 }
33 else
34 {
35 return substr($str, 0, $r_len-1);
36 }
37 }
20、将上传文件转移到指定位置
1 /**
2 * 将上传文件转移到指定位置
3 *
4 * @param string $file_name
5 * @param string $target_name
6 * @return blog
7 */
8 function move_upload_file($file_name, $target_name = '')
9 {
10 if (function_exists("move_uploaded_file"))
11 {
12 if (move_uploaded_file($file_name, $target_name))
13 {
14 @chmod($target_name,0755);
15 return true;
16 }
17 else if (copy($file_name, $target_name))
18 {
19 @chmod($target_name,0755);
20 return true;
21 }
22 }
23 elseif (copy($file_name, $target_name))
24 {
25 @chmod($target_name,0755);
26 return true;
27 }
28 return false;
29 }
21、将JSON传递的参数转码
1 /**
2 * 将JSON传递的参数转码
3 *
4 * @param string $str
5 * @return string
6 */
7 function json_str_iconv($str)
8 {
9 if (EC_CHARSET != 'utf-8')
10 {
11 if (is_string($str))
12 {
13 return addslashes(stripslashes(ecs_iconv('utf-8', EC_CHARSET, $str)));
14 }
15 elseif (is_array($str))
16 {
17 foreach ($str as $key => $value)
18 {
19 $str[$key] = json_str_iconv($value);
20 }
21 return $str;
22 }
23 elseif (is_object($str))
24 {
25 foreach ($str as $key => $value)
26 {
27 $str->$key = json_str_iconv($value);
28 }
29 return $str;
30 }
31 else
32 {
33 return $str;
34 }
35 }
36 return $str;
37 }
22、循环转码成utf8内容
1 /**
2 * 循环转码成utf8内容
3 *
4 * @param string $str
5 * @return string
6 */
7 function to_utf8_iconv($str)
8 {
9 if (EC_CHARSET != 'utf-8')
10 {
11 if (is_string($str))
12 {
13 return ecs_iconv(EC_CHARSET, 'utf-8', $str);
14 }
15 elseif (is_array($str))
16 {
17 foreach ($str as $key => $value)
18 {
19 $str[$key] = to_utf8_iconv($value);
20 }
21 return $str;
22 }
23 elseif (is_object($str))
24 {
25 foreach ($str as $key => $value)
26 {
27 $str->$key = to_utf8_iconv($value);
28 }
29 return $str;
30 }
31 else
32 {
33 return $str;
34 }
35 }
36 return $str;
37 }
23、获取文件后缀名,并判断是否合法
1 /**
2 * 获取文件后缀名,并判断是否合法
3 *
4 * @param string $file_name
5 * @param array $allow_type
6 * @return blob
7 */
8 function get_file_suffix($file_name, $allow_type = array())
9 {
10 $file_suffix = strtolower(array_pop(explode('.', $file_name)));
11 if (empty($allow_type))
12 {
13 return $file_suffix;
14 }
15 else
16 {
17 if (in_array($file_suffix, $allow_type))
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25 }
26 }
24、 读结果缓存文件
1 /**
2 * 读结果缓存文件
3 *
4 * @params string $cache_name
5 *
6 * @return array $data
7 */
8 function read_static_cache($cache_name)
9 {
10 if ((DEBUG_MODE & 2) == 2)
11 {
12 return false;
13 }
14 static $result = array();
15 if (!empty($result[$cache_name]))
16 {
17 return $result[$cache_name];
18 }
19 $cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php';
20 if (file_exists($cache_file_path))
21 {
22 include_once($cache_file_path);
23 $result[$cache_name] = $data;
24 return $result[$cache_name];
25 }
26 else
27 {
28 return false;
29 }
30 }
25、 写结果缓存文件
1 /**
2 * 写结果缓存文件
3 *
4 * @params string $cache_name
5 * @params string $caches
6 *
7 * @return
8 */
9 function write_static_cache($cache_name, $caches)
10 {
11 if ((DEBUG_MODE & 2) == 2)
12 {
13 return false;
14 }
15 $cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php';
16 $content = "<?php\r\n";
17 $content .= "\$data = " . var_export($caches, true) . ";\r\n";
18 $content .= "?>";
19 file_put_contents($cache_file_path, $content, LOCK_EX);
20 }