当前位置:Gxlcms > PHP教程 > 最完整PHP常用工具类大全

最完整PHP常用工具类大全

时间:2021-07-01 10:21:17 帮助过:35人阅读

  1. <!--?php
  2. /**
  3. * 助手类
  4. * @author www.shouce.ren
  5. */
  6. class Helper
  7. {
  8. /**
  9. * 判断当前服务器系统
  10. * @return string
  11. */
  12. public static function getOS(){
  13. if(PATH_SEPARATOR == ':'){
  14. return 'Linux';
  15. }else{
  16. return 'Windows';
  17. }
  18. }
  19. /**
  20. * 当前微妙数
  21. * @return number
  22. */
  23. public static function microtime_float() {
  24. list ( $usec, $sec ) = explode ( " ", microtime () );
  25. return (( float ) $usec + ( float ) $sec);
  26. }
  27. /**
  28. * 切割utf-8格式的字符串(一个汉字或者字符占一个字节)
  29. *
  30. * @author zhao jinhan
  31. * @version v1.0.0
  32. *
  33. */
  34. public static function truncate_utf8_string($string, $length, $etc = '...') {
  35. $result = '';
  36. $string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, 'UTF-8' );
  37. $strlen = strlen ( $string );
  38. for($i = 0; (($i < $strlen) && ($length --> 0)); $i ++) {
  39. if ($number = strpos ( str_pad ( decbin ( ord ( substr ( $string, $i, 1 ) ) ), 8, '0', STR_PAD_LEFT ), '0' )) {
  40. if ($length < 1.0) {
  41. break;
  42. }
  43. $result .= substr ( $string, $i, $number );
  44. $length -= 1.0;
  45. $i += $number - 1;
  46. } else {
  47. $result .= substr ( $string, $i, 1 );
  48. $length -= 0.5;
  49. }
  50. }
  51. $result = htmlspecialchars ( $result, ENT_QUOTES, 'UTF-8' );
  52. if ($i < $strlen) {
  53. $result .= $etc;
  54. }
  55. return $result;
  56. }
  57. /**
  58. * 遍历文件夹
  59. * @param string $dir
  60. * @param boolean $all true表示递归遍历
  61. * @return array
  62. */
  63. public static function scanfDir($dir='', $all = false, &$ret = array()){
  64. if ( false !== ($handle = opendir ( $dir ))) {
  65. while ( false !== ($file = readdir ( $handle )) ) {
  66. if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {
  67. $cur_path = $dir . '/' . $file;
  68. if (is_dir ( $cur_path )) {
  69. $ret['dirs'][] =$cur_path;
  70. $all && self::scanfDir( $cur_path, $all, $ret);
  71. } else {
  72. $ret ['files'] [] = $cur_path;
  73. }
  74. }
  75. }
  76. closedir ( $handle );
  77. }
  78. return $ret;
  79. }
  80. /**
  81. * 邮件发送
  82. * @param string $toemail
  83. * @param string $subject
  84. * @param string $message
  85. * @return boolean
  86. */
  87. public static function sendMail($toemail = '', $subject = '', $message = '') {
  88. $mailer = Yii::createComponent ( 'application.extensions.mailer.EMailer' );
  89. //邮件配置
  90. $mailer->SetLanguage('zh_cn');
  91. $mailer->Host = Yii::app()->params['emailHost']; //<strong>发送邮件</strong>服务器
  92. $mailer->Port = Yii::app()->params['emailPort']; //邮件端口
  93. $mailer->Timeout = Yii::app()->params['emailTimeout'];//邮件发送超时时间
  94. $mailer->ContentType = 'text/html';//设置html格式
  95. $mailer->SMTPAuth = true;
  96. $mailer->Username = Yii::app()->params['emailUserName'];
  97. $mailer->Password = Yii::app()->params['emailPassword'];
  98. $mailer->IsSMTP ();
  99. $mailer->From = $mailer->Username; // 发件人邮箱
  100. $mailer->FromName = Yii::app()->params['emailFormName']; // 发件人姓名
  101. $mailer->AddReplyTo ( $mailer->Username );
  102. $mailer->CharSet = 'UTF-8';
  103. // 添加邮件日志
  104. $modelMail = new MailLog ();
  105. $modelMail->accept = $toemail;
  106. $modelMail->subject = $subject;
  107. $modelMail->message = $message;
  108. $modelMail->send_status = 'waiting';
  109. $modelMail->save ();
  110. // <strong>发送邮件</strong>
  111. $mailer->AddAddress ( $toemail );
  112. $mailer->Subject = $subject;
  113. $mailer->Body = $message;
  114. if ($mailer->Send () === true) {
  115. $modelMail->times = $modelMail->times + 1;
  116. $modelMail->send_status = 'success';
  117. $modelMail->save ();
  118. return true;
  119. } else {
  120. $error = $mailer->ErrorInfo;
  121. $modelMail->times = $modelMail->times + 1;
  122. $modelMail->send_status = 'failed';
  123. $modelMail->error = $error;
  124. $modelMail->save ();
  125. return false;
  126. }
  127. }
  128. /**
  129. * 判断字符串是utf-8 还是<strong>GB2312</strong>
  130. * @param unknown $str
  131. * @param string $default
  132. * @return string
  133. */
  134. public static function utf8_<strong>GB2312</strong>($str, $default = '<strong>GB2312</strong>')
  135. {
  136. $str = preg_replace("/[\x01-\x7F]+/", "", $str);
  137. if (empty($str)) return $default;
  138. $preg = array(
  139. "<strong>GB2312</strong>" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是<strong>GB2312</strong>
  140. "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u", //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
  141. );
  142. if ($default == '<strong>GB2312</strong>') {
  143. $option = 'utf-8';
  144. } else {
  145. $option = '<strong>GB2312</strong>';
  146. }
  147. if (!preg_match($preg[$default], $str)) {
  148. return $option;
  149. }
  150. $str = @iconv($default, $option, $str);
  151. //不能转成 $option, 说明原来的不是 $default
  152. if (empty($str)) {
  153. return $option;
  154. }
  155. return $default;
  156. }
  157. /**
  158. * utf-8和<strong>GB2312</strong>自动转化
  159. * @param unknown $string
  160. * @param string $outEncoding
  161. * @return unknown|string
  162. */
  163. public static function safeEncoding($string,$outEncoding = 'UTF-8')
  164. {
  165. $encoding = "UTF-8";
  166. for($i = 0; $i < strlen ( $string ); $i ++) {
  167. if (ord ( $string {$i} ) < 128)
  168. continue;
  169. if ((ord ( $string {$i} ) & 224) == 224) {
  170. // 第一个字节判断通过
  171. $char = $string {++ $i};
  172. if ((ord ( $char ) & 128) == 128) {
  173. // 第二个字节判断通过
  174. $char = $string {++ $i};
  175. if ((ord ( $char ) & 128) == 128) {
  176. $encoding = "UTF-8";
  177. break;
  178. }
  179. }
  180. }
  181. if ((ord ( $string {$i} ) & 192) == 192) {
  182. // 第一个字节判断通过
  183. $char = $string {++ $i};
  184. if ((ord ( $char ) & 128) == 128) {
  185. // 第二个字节判断通过
  186. $encoding = "<strong>GB2312</strong>";
  187. break;
  188. }
  189. }
  190. }
  191. if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))
  192. return $string;
  193. else
  194. return @iconv ( $encoding, $outEncoding, $string );
  195. }
  196. /**
  197. * 返回二维数组中某个键名的所有值
  198. * @param input $array
  199. * @param string $key
  200. * @return array
  201. */
  202. public static function array_key_values($array =array(), $key='')
  203. {
  204. $ret = array();
  205. foreach((array)$array as $k=>$v){
  206. $ret[$k] = $v[$key];
  207. }
  208. return $ret;
  209. }
  210. /**
  211. * 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数)
  212. * @param string $file 文件/目录
  213. * @return boolean
  214. */
  215. public static function is_writeable($file) {
  216. if (is_dir($file)){
  217. $dir = $file;
  218. if ($fp = @fopen("$dir/test.txt", 'w')) {
  219. @fclose($fp);
  220. @unlink("$dir/test.txt");
  221. $writeable = 1;
  222. } else {
  223. $writeable = 0;
  224. }
  225. } else {
  226. if ($fp = @fopen($file, 'a+')) {
  227. @fclose($fp);
  228. $writeable = 1;
  229. } else {
  230. $writeable = 0;
  231. }
  232. }
  233. return $writeable;
  234. }
  235. /**
  236. * 格式化单位
  237. */
  238. static public function byteFormat( $size, $dec = 2 ) {
  239. $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );
  240. $pos = 0;
  241. while ( $size >= 1024 ) {
  242. $size /= 1024;
  243. $pos ++;
  244. }
  245. return round( $size, $dec ) . " " . $a[$pos];
  246. }
  247. /**
  248. * 下拉框,单选按钮 自动选择
  249. *
  250. * @param $string 输入字符
  251. * @param $param 条件
  252. * @param $type 类型
  253. * selected checked
  254. * @return string
  255. */
  256. static public function selected( $string, $param = 1, $type = 'select' ) {
  257. $true = false;
  258. if ( is_array( $param ) ) {
  259. $true = in_array( $string, $param );
  260. }elseif ( $string == $param ) {
  261. $true = true;
  262. }
  263. $return='';
  264. if ( $true )
  265. $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';
  266. echo $return;
  267. }
  268. /**
  269. * 下载远程图片
  270. * @param string $url 图片的绝对url
  271. * @param string $filepath 文件的完整路径(例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名
  272. * @param string $filename 要保存的文件名(不含扩展名)
  273. * @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false
  274. */
  275. static public function downloadImage($url, $filepath, $filename) {
  276. //服务器返回的头信息
  277. $responseHeaders = array();
  278. //原始图片名
  279. $originalfilename = '';
  280. //图片的后缀名
  281. $ext = '';
  282. $ch = curl_init($url);
  283. //设置curl_exec返回的值包含Http头
  284. curl_setopt($ch, CURLOPT_HEADER, 1);
  285. //设置curl_exec返回的值包含Http内容
  286. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  287. //设置抓取跳转(http 301,302)后的页面
  288. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  289. //设置最多的HTTP重定向的数量
  290. curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
  291. //服务器返回的数据(包括http头信息和内容)
  292. $html = curl_exec($ch);
  293. //获取此次抓取的相关信息
  294. $httpinfo = curl_getinfo($ch);
  295. curl_close($ch);
  296. if ($html !== false) {
  297. //分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串
  298. $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
  299. //倒数第二段是服务器最后一次response的http头
  300. $header = $httpArr[count($httpArr) - 2];
  301. //倒数第一段是服务器最后一次response的内容
  302. $body = $httpArr[count($httpArr) - 1];
  303. $header.="\r\n";
  304. //获取最后一次response的header信息
  305. preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);
  306. if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {
  307. for ($i = 0; $i < count($matches[1]); $i++) {
  308. if (array_key_exists($i, $matches[2])) {
  309. $responseHeaders[$matches[1][$i]] = $matches[2][$i];
  310. }
  311. }
  312. }
  313. //获取图片后缀名
  314. if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {
  315. $originalfilename = $matches[0];
  316. $ext = $matches[1];
  317. } else {
  318. if (array_key_exists('Content-Type', $responseHeaders)) {
  319. if (0 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {
  320. $ext = $extmatches[1];
  321. }
  322. }
  323. }
  324. //保存文件
  325. if (!empty($ext)) {
  326. //如果目录不存在,则先要创建目录
  327. if(!is_dir($filepath)){
  328. mkdir($filepath, 0777, true);
  329. }
  330. $filepath .= '/'.$filename.".$ext";
  331. $local_file = fopen($filepath, 'w');
  332. if (false !== $local_file) {
  333. if (false !== fwrite($local_file, $body)) {
  334. fclose($local_file);
  335. $sizeinfo = getimagesize($filepath);
  336. return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));
  337. }
  338. }
  339. }
  340. }
  341. return false;
  342. }
  343. /**
  344. * 查找ip是否在某个段位里面
  345. * @param string $ip 要查询的ip
  346. * @param $arrIP 禁止的ip
  347. * @return boolean
  348. */
  349. public static function ipAccess($ip='0.0.0.0', $arrIP = array()){
  350. $access = true;
  351. $ip && $arr_cur_ip = explode('.', $ip);
  352. foreach((array)$arrIP as $key=> $value){
  353. if($value == '*.*.*.*'){
  354. $access = false; //禁止所有
  355. break;
  356. }
  357. $tmp_arr = explode('.', $value);
  358. if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {
  359. //前两段相同
  360. if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){
  361. //第三段为* 或者相同
  362. if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){
  363. //第四段为* 或者相同
  364. $access = false; //在禁止ip列,则禁止访问
  365. break;
  366. }
  367. }
  368. }
  369. }
  370. return $access;
  371. }
  372. /**
  373. * @param string $string 原文或者密文
  374. * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
  375. * @param string $key 密钥
  376. * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
  377. * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
  378. *
  379. * @example
  380. *
  381. * $a = authcode('abc', 'ENCODE', 'key');
  382. * $b = authcode($a, 'DECODE', 'key'); // $b(abc)
  383. *
  384. * $a = authcode('abc', 'ENCODE', 'key', 3600);
  385. * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空
  386. */
  387. public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {
  388. $ckey_length = 4;
  389. // 随机密钥长度 取值 0-32;
  390. // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
  391. // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
  392. // 当此值为 0 时,则不产生随机密钥
  393. $key = md5 ( $key ? $key : 'key' ); //这里可以填写默认key值
  394. $keya = md5 ( substr ( $key, 0, 16 ) );
  395. $keyb = md5 ( substr ( $key, 16, 16 ) );
  396. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';
  397. $cryptkey = $keya . md5 ( $keya . $keyc );
  398. $key_length = strlen ( $cryptkey );
  399. $string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
  400. $string_length = strlen ( $string );
  401. $result = '';
  402. $box = range ( 0, 255 );
  403. $rndkey = array ();
  404. for($i = 0; $i <= 255; $i ++) {
  405. $rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
  406. }
  407. for($j = $i = 0; $i < 256; $i ++) {
  408. $j = ($j + $box [$i] + $rndkey [$i]) % 256;
  409. $tmp = $box [$i];
  410. $box [$i] = $box [$j];
  411. $box [$j] = $tmp;
  412. }
  413. for($a = $j = $i = 0; $i < $string_length; $i ++) {
  414. $a = ($a + 1) % 256;
  415. $j = ($j + $box [$a]) % 256;
  416. $tmp = $box [$a];
  417. $box [$a] = $box [$j];
  418. $box [$j] = $tmp;
  419. $result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
  420. }
  421. if ($operation == 'DECODE') {
  422. if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
  423. return substr ( $result, 26 );
  424. } else {
  425. return '';
  426. }
  427. } else {
  428. return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
  429. }
  430. }
  431. public static function gbkToUtf8($str){
  432. return iconv("GBK", "UTF-8", $str);
  433. }
  434. /**
  435. * 取得输入目录所包含的所有目录和文件
  436. * 以关联数组形式返回
  437. * author: flynetcn
  438. */
  439. static public function deepScanDir($dir)
  440. {
  441. $fileArr = array();
  442. $dirArr = array();
  443. $dir = rtrim($dir, '//');
  444. if(is_dir($dir)){
  445. $dirHandle = opendir($dir);
  446. while(false !== ($fileName = readdir($dirHandle))){
  447. $subFile = $dir . DIRECTORY_SEPARATOR . $fileName;
  448. if(is_file($subFile)){
  449. $fileArr[] = $subFile;
  450. } elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){
  451. $dirArr[] = $subFile;
  452. $arr = self::deepScanDir($subFile);
  453. $dirArr = array_merge($dirArr, $arr['dir']);
  454. $fileArr = array_merge($fileArr, $arr['file']);
  455. }
  456. }
  457. closedir($dirHandle);
  458. }
  459. return array('dir'=>$dirArr, 'file'=>$fileArr);
  460. }
  461. /**
  462. * 取得输入目录所包含的所有文件
  463. * 以数组形式返回
  464. * author: flynetcn
  465. */
  466. static public function get_dir_files($dir)
  467. {
  468. if (is_file($dir)) {
  469. return array($dir);
  470. }
  471. $files = array();
  472. if (is_dir($dir) && ($dir_p = opendir($dir))) {
  473. $ds = DIRECTORY_SEPARATOR;
  474. while (($filename = readdir($dir_p)) !== false) {
  475. if ($filename=='.' || $filename=='..') { continue; }
  476. $filetype = filetype($dir.$ds.$filename);
  477. if ($filetype == 'dir') {
  478. $files = array_merge($files, self::get_dir_files($dir.$ds.$filename));
  479. } elseif ($filetype == 'file') {
  480. $files[] = $dir.$ds.$filename;
  481. }
  482. }
  483. closedir($dir_p);
  484. }
  485. return $files;
  486. }
  487. /**
  488. * 删除文件夹及其文件夹下所有文件
  489. */
  490. public static function deldir($dir) {
  491. //先删除目录下的文件:
  492. $dh=opendir($dir);
  493. while ($file=readdir($dh)) {
  494. if($file!="." && $file!="..") {
  495. $fullpath=$dir."/".$file;
  496. if(!is_dir($fullpath)) {
  497. unlink($fullpath);
  498. } else {
  499. self::deldir($fullpath);
  500. }
  501. }
  502. }
  503. closedir($dh);
  504. //删除当前文件夹:
  505. if(rmdir($dir)) {
  506. return true;
  507. } else {
  508. return false;
  509. }
  510. }
  511. /**
  512. * js 弹窗并且跳转
  513. * @param string $_info
  514. * @param string $_url
  515. * @return js
  516. */
  517. static public function alertLocation($_info, $_url) {
  518. echo "";
  519. exit();
  520. }
  521. /**
  522. * js 弹窗返回
  523. * @param string $_info
  524. * @return js
  525. */
  526. static public function alertBack($_info) {
  527. echo "";
  528. exit();
  529. }
  530. /**
  531. * 页面跳转
  532. * @param string $url
  533. * @return js
  534. */
  535. static public function headerUrl($url) {
  536. echo "";
  537. exit();
  538. }
  539. /**
  540. * 弹窗关闭
  541. * @param string $_info
  542. * @return js
  543. */
  544. static public function alertClose($_info) {
  545. echo "";
  546. exit();
  547. }
  548. /**
  549. * 弹窗
  550. * @param string $_info
  551. * @return js
  552. */
  553. static public function alert($_info) {
  554. echo "";
  555. exit();
  556. }
  557. /**
  558. * 系统基本参数上传图片专用
  559. * @param string $_path
  560. * @return null
  561. */
  562. static public function sysUploadImg($_path) {
  563. echo '';
  564. echo '';
  565. echo '';
  566. echo '';
  567. }
  568. /**
  569. * html过滤
  570. * @param array|object $_date
  571. * @return string
  572. */
  573. static public function htmlString($_date) {
  574. if (is_array($_date)) {
  575. foreach ($_date as $_key=>$_value) {
  576. $_string[$_key] = self::htmlString($_value); //递归
  577. }
  578. } elseif (is_object($_date)) {
  579. foreach ($_date as $_key=>$_value) {
  580. $_string->$_key = self::htmlString($_value); //递归
  581. }
  582. } else {
  583. $_string = htmlspecialchars($_date);
  584. }
  585. return $_string;
  586. }
  587. /**
  588. * 数据库输入过滤
  589. * @param string $_data
  590. * @return string
  591. */
  592. static public function mysqlString($_data) {
  593. $_data = trim($_data);
  594. return !GPC ? addcslashes($_data) : $_data;
  595. }
  596. /**
  597. * 清理session
  598. */
  599. static public function unSession() {
  600. if (session_start()) {
  601. session_destroy();
  602. }
  603. }
  604. /**
  605. * 验证是否为空
  606. * @param string $str
  607. * @param string $name
  608. * @return bool (true or false)
  609. */
  610. static function validateEmpty($str, $name) {
  611. if (empty($str)) {
  612. self::alertBack('警告:' .$name . '不能为空!');
  613. }
  614. }
  615. /**
  616. * 验证是否相同
  617. * @param string $str1
  618. * @param string $str2
  619. * @param string $alert
  620. * @return JS
  621. */
  622. static function validateAll($str1, $str2, $alert) {
  623. if ($str1 != $str2) self::alertBack('警告:' .$alert);
  624. }
  625. /**
  626. * 验证ID
  627. * @param Number $id
  628. * @return JS
  629. */
  630. static function validateId($id) {
  631. if (empty($id) || !is_numeric($id)) self::alertBack('警告:参数错误!');
  632. }
  633. /**
  634. * 格式化字符串
  635. * @param string $str
  636. * @return string
  637. */
  638. static public function formatStr($str) {
  639. $arr = array(' ', '
  640. ', '&', '@', '#', '%', '\'', '"', '\\', '/', '.', ',', '$', '^', '*', '(', ')', '[', ']', '{', '}', '|', '~', '`', '?', '!', ';', ':', '-', '_', '+', '=');
  641. foreach ($arr as $v) {
  642. $str = str_replace($v, '', $str);
  643. }
  644. return $str;
  645. }
  646. /**
  647. * 格式化时间
  648. * @param int $time 时间戳
  649. * @return string
  650. */
  651. static public function formatDate($time='default') {
  652. $date = $time == 'default' ? date('Y-m-d H:i:s', time()) : date('Y-m-d H:i:s', $time);
  653. return $date;
  654. }
  655. /**
  656. * 获得真实IP地址
  657. * @return string
  658. */
  659. static public function realIp() {
  660. static $realip = NULL;
  661. if ($realip !== NULL) return $realip;
  662. if (isset($_SERVER)) {
  663. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  664. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  665. foreach ($arr AS $ip) {
  666. $ip = trim($ip);
  667. if ($ip != 'unknown') {
  668. $realip = $ip;
  669. break;
  670. }
  671. }
  672. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  673. $realip = $_SERVER['HTTP_CLIENT_IP'];
  674. } else {
  675. if (isset($_SERVER['REMOTE_ADDR'])) {
  676. $realip = $_SERVER['REMOTE_ADDR'];
  677. } else {
  678. $realip = '0.0.0.0';
  679. }
  680. }
  681. } else {
  682. if (getenv('HTTP_X_FORWARDED_FOR')) {
  683. $realip = getenv('HTTP_X_FORWARDED_FOR');
  684. } elseif (getenv('HTTP_CLIENT_IP')) {
  685. $realip = getenv('HTTP_CLIENT_IP');
  686. } else {
  687. $realip = getenv('REMOTE_ADDR');
  688. }
  689. }
  690. preg_match('/[\d\.]{7,15}/', $realip, $onlineip);
  691. $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
  692. return $realip;
  693. }
  694. /**
  695. * 加载 Smarty 模板
  696. * @param string $html
  697. * @return null;
  698. */
  699. static public function display() {
  700. global $tpl;$html = null;
  701. $htmlArr = explode('/', $_SERVER[SCRIPT_NAME]);
  702. $html = str_ireplace('.php', '.html', $htmlArr[count($htmlArr)-1]);
  703. $dir = dirname($_SERVER[SCRIPT_NAME]);
  704. $firstStr = substr($dir, 0, 1);
  705. $endStr = substr($dir, strlen($dir)-1, 1);
  706. if ($firstStr == '/' || $firstStr == '\\') $dir = substr($dir, 1);
  707. if ($endStr != '/' || $endStr != '\\') $dir = $dir . '/';
  708. $tpl->display($dir.$html);
  709. }
  710. /**
  711. * 创建目录
  712. * @param string $dir
  713. */
  714. static public function createDir($dir) {
  715. if (!is_dir($dir)) {
  716. mkdir($dir, 0777);
  717. }
  718. }
  719. /**
  720. * 创建文件(默认为空)
  721. * @param unknown_type $filename
  722. */
  723. static public function createFile($filename) {
  724. if (!is_file($filename)) touch($filename);
  725. }
  726. /**
  727. * 正确获取变量
  728. * @param string $param
  729. * @param string $type
  730. * @return string
  731. */
  732. static public function getData($param, $type='post') {
  733. $type = strtolower($type);
  734. if ($type=='post') {
  735. return self::mysqlString(trim($_POST[$param]));
  736. } elseif ($type=='get') {
  737. return self::mysqlString(trim($_GET[$param]));
  738. }
  739. }
  740. /**
  741. * 删除文件
  742. * @param string $filename
  743. */
  744. static public function delFile($filename) {
  745. if (file_exists($filename)) unlink($filename);
  746. }
  747. /**
  748. * 删除目录
  749. * @param string $path
  750. */
  751. static public function delDir($path) {
  752. if (is_dir($path)) rmdir($path);
  753. }
  754. /**
  755. * 删除目录及地下的全部文件
  756. * @param string $dir
  757. * @return bool
  758. */
  759. static public function delDirOfAll($dir) {
  760. //先删除目录下的文件:
  761. if (is_dir($dir)) {
  762. $dh=opendir($dir);
  763. while (!!$file=readdir($dh)) {
  764. if($file!="." && $file!="..") {
  765. $fullpath=$dir."/".$file;
  766. if(!is_dir($fullpath)) {
  767. unlink($fullpath);
  768. } else {
  769. self::delDirOfAll($fullpath);
  770. }
  771. }
  772. }
  773. closedir($dh);
  774. //删除当前文件夹:
  775. if(rmdir($dir)) {
  776. return true;
  777. } else {
  778. return false;
  779. }
  780. }
  781. }
  782. /**
  783. * 验证登陆
  784. */
  785. static public function validateLogin() {
  786. if (empty($_SESSION['admin']['user'])) header('Location:/admin/');
  787. }
  788. /**
  789. * 给已经存在的图片添加水印
  790. * @param string $file_path
  791. * @return bool
  792. */
  793. static public function addMark($file_path) {
  794. if (file_exists($file_path) && file_exists(MARK)) {
  795. //求出上传图片的名称后缀
  796. $ext_name = strtolower(substr($file_path, strrpos($file_path, '.'), strlen($file_path)));
  797. //$new_name='jzy_' . time() . rand(1000,9999) . $ext_name ;
  798. $store_path = ROOT_PATH . UPDIR;
  799. //求上传图片高宽
  800. $imginfo = getimagesize($file_path);
  801. $width = $imginfo[0];
  802. $height = $imginfo[1];
  803. //添加图片水印
  804. switch($ext_name) {
  805. case '.gif':
  806. $dst_im = imagecreatefromgif($file_path);
  807. break;
  808. case '.jpg':
  809. $dst_im = imagecreatefromjpeg($file_path);
  810. break;
  811. case '.png':
  812. $dst_im = imagecreatefrompng($file_path);
  813. break;
  814. }
  815. $src_im = imagecreatefrompng(MARK);
  816. //求<strong>水印图片</strong>高宽
  817. $src_imginfo = getimagesize(MARK);
  818. $src_width = $src_imginfo[0];
  819. $src_height = $src_imginfo[1];
  820. //求出<strong>水印图片</strong>的实际生成位置
  821. $src_x = $width - $src_width - 10;
  822. $src_y = $height - $src_height - 10;
  823. //新建一个真彩色图像
  824. $nimage = imagecreatetruecolor($width, $height);
  825. //拷贝上传图片到真彩图像
  826. imagecopy($nimage, $dst_im, 0, 0, 0, 0, $width, $height);
  827. //按坐标位置拷贝<strong>水印图片</strong>到真彩图像上
  828. imagecopy($nimage, $src_im, $src_x, $src_y, 0, 0, $src_width, $src_height);
  829. //分情况
输出生成后的水印图片 switch($ext_name) { case '.gif': imagegif($nimage, $file_path); break; case '.jpg': imagejpeg($nimage, $file_path); break; case '.png': imagepng($nimage, $file_path); break; } //释放资源 imagedestroy($dst_im); imagedestroy($src_im); unset($imginfo); unset($src_imginfo); //移动生成后的图片 @move_uploaded_file($file_path, ROOT_PATH.UPDIR . $file_path); } } /** * 中文截取2,单字节截取模式 * @access public * @param string $str 需要截取的字符串 * @param int $slen 截取的长度 * @param int $startdd 开始标记处 * @return string */ static public function cn_substr($str, $slen, $startdd=0){ $cfg_soft_lang = PAGECHARSET; if($cfg_soft_lang=='utf-8') { return self::cn_substr_utf8($str, $slen, $startdd); } $restr = ''; $c = ''; $str_len = strlen($str); if($str_len < $startdd+1) { return ''; } if($str_len < $startdd + $slen || $slen==0) { $slen = $str_len - $startdd; } $enddd = $startdd + $slen - 1; for($i=0;$i<$str_len;$i++) { if($startdd==0) { $restr .= $c; } elseif($i > $startdd) { $restr .= $c; } if(ord($str[$i])>0x80) { if($str_len>$i+1) { $c = $str[$i].$str[$i+1]; } $i++; } else { $c = $str[$i]; } if($i >= $enddd) { if(strlen($restr)+strlen($c)>$slen) { break; } else { $restr .= $c; break; } } } return $restr; } /** * utf-8中文截取,单字节截取模式 * * @access public * @param string $str 需要截取的字符串 * @param int $slen 截取的长度 * @param int $startdd 开始标记处 * @return string */ static public function cn_substr_utf8($str, $length, $start=0) { if(strlen($str) < $start+1) { return ''; } preg_match_all("/./su", $str, $ar); $str = ''; $tstr = ''; //为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取 for($i=0; isset($ar[0][$i]); $i++) { if(strlen($tstr) < $start) { $tstr .= $ar[0][$i]; } else { if(strlen($str) < $length + strlen($ar[0][$i]) ) { $str .= $ar[0][$i]; } else { break; } } } return $str; } /** * 删除图片,根据图片ID * @param int $image_id */ static function delPicByImageId($image_id) { $db_name = PREFIX . 'images i'; $m = new Model(); $data = $m->getOne($db_name, "i.id={$image_id}", "i.path as p, i.big_img as b, i.small_img as s"); foreach ($data as $v) { @self::delFile(ROOT_PATH . $v['p']); @self::delFile(ROOT_PATH . $v['b']); @self::delFile(ROOT_PATH . $v['s']); } $m->del(PREFIX . 'images', "id={$image_id}"); unset($m); } /** * 图片等比例缩放 * @param resource $im 新建图片资源(imagecreatefromjpeg/imagecreatefrompng/imagecreatefromgif) * @param int $maxwidth 生成图像宽 * @param int $maxheight 生成图像高 * @param string $name 生成图像名称 * @param string $filetype文件类型(.jpg/.gif/.png) */ static public function resizeImage($im, $maxwidth, $maxheight, $name, $filetype) { $pic_width = imagesx($im); $pic_height = imagesy($im); if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) { if($maxwidth && $pic_width>$maxwidth) { $widthratio = $maxwidth/$pic_width; $resizewidth_tag = true; } if($maxheight && $pic_height>$maxheight) { $heightratio = $maxheight/$pic_height; $resizeheight_tag = true; } if($resizewidth_tag && $resizeheight_tag) { if($widthratio<$heightratio) $ratio = $widthratio; else $ratio = $heightratio; } if($resizewidth_tag && !$resizeheight_tag) $ratio = $widthratio; if($resizeheight_tag && !$resizewidth_tag) $ratio = $heightratio; $newwidth = $pic_width * $ratio; $newheight = $pic_height * $ratio; if(function_exists("imagecopyresampled")) { $newim = imagecreatetruecolor($newwidth,$newheight); imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height); } else { $newim = imagecreate($newwidth,$newheight); imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height); } $name = $name.$filetype; imagejpeg($newim,$name); imagedestroy($newim); } else { $name = $name.$filetype; imagejpeg($im,$name); } } /** * 下载文件 * @param string $file_path 绝对路径 */ static public function downFile($file_path) { //判断文件是否存在 $file_path = iconv('utf-8', 'GB2312', $file_path); //对可能出现的中文名称进行转码 if (!file_exists($file_path)) { exit('文件不存在!'); } $file_name = basename($file_path); //获取文件名称 $file_size = filesize($file_path); //获取文件大小 $fp = fopen($file_path, 'r'); //以只读的方式打开文件 header("Content-type: application/octet-stream"); header("Accept-Ranges: bytes"); header("Accept-Length: {$file_size}"); header("Content-Disposition: attachment;filename={$file_name}"); $buffer = 1024; $file_count = 0; //判断文件是否结束 while (!feof($fp) && ($file_size-$file_count>0)) { $file_data = fread($fp, $buffer); $file_count += $buffer; echo $file_data; } fclose($fp); //关闭文件 } }

下载地址 http://www.shouce.ren/post/view/id/1700

以上就介绍了最完整PHP常用工具类大全,包括了水印图片,发送邮件,GB2312方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行