全国服务热线:400-6566-535 广州热线:020-82105691 客服QQ:858560031
后台演示 猪八戒 阿里巴巴商铺 手机版
网络营销电子商务建站知识编程知识行业资讯SEO知识常见问题网络安全
您当前位置: 首页 >资讯活动 > PHP开发 > PHP常用工具类大全

PHP常用工具类大全

时间:2015-12-13 作者:七想网络

 

这是项目中使用的PHP工具类现在分享给大家,基本上常用到的都有。


  1. <?php

  2. /**

  3.  * 助手类

  4.  * @author www.shouce.ren

  5.  *

  6.  */

  7. class Helper

  8. {

  9. /**

  10. * 判断当前服务器系统

  11. * @return string

  12. */

  13. public static function getOS(){

  14. if(PATH_SEPARATOR == ':'){

  15. return 'Linux';

  16. }else{

  17. return 'Windows';

  18. }

  19. }

  20. /**

  21. * 当前微妙数

  22. * @return number

  23. */

  24. public static function microtime_float() {

  25. list ( $usec, $sec ) = explode ( " ", microtime () );

  26. return (( float ) $usec + ( float ) $sec);

  27. }

  28.  

  29. /**

  30. * 切割utf-8格式的字符串(一个汉字或者字符占一个字节)

  31. *

  32. * @author zhao jinhan

  33. * @version v1.0.0

  34. *

  35. */

  36. public static function truncate_utf8_string($string, $length, $etc = '...') {

  37. $result = '';

  38. $string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, 'UTF-8' );

  39. $strlen = strlen ( $string );

  40. for($i = 0; (($i < $strlen) && ($length > 0)); $i ++) {

  41. if ($number = strpos ( str_pad ( decbin ( ord ( substr ( $string, $i, 1 ) ) ), 8, '0', STR_PAD_LEFT ), '0' )) {

  42. if ($length < 1.0) {

  43. break;

  44. }

  45. $result .= substr ( $string, $i, $number );

  46. $length -= 1.0;

  47. $i += $number - 1;

  48. } else {

  49. $result .= substr ( $string, $i, 1 );

  50. $length -= 0.5;

  51. }

  52. }

  53. $result = htmlspecialchars ( $result, ENT_QUOTES, 'UTF-8' );

  54. if ($i < $strlen) {

  55. $result .= $etc;

  56. }

  57. return $result;

  58. }

  59.  

  60. /**

  61. * 遍历文件夹

  62. * @param string $dir

  63. * @param boolean $all  true表示递归遍历

  64. * @return array

  65. */

  66. public static function scanfDir($dir='', $all = false, &$ret = array()){

  67. if ( false !== ($handle = opendir ( $dir ))) {

  68. while ( false !== ($file = readdir ( $handle )) ) {

  69. if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {

  70. $cur_path = $dir . '/' . $file;

  71. if (is_dir ( $cur_path )) {

  72. $ret['dirs'][] =$cur_path;

  73. $all && self::scanfDir( $cur_path, $all, $ret);

  74. } else {

  75. $ret ['files'] [] = $cur_path;

  76. }

  77. }

  78. }

  79. closedir ( $handle );

  80. }

  81. return $ret;

  82. }

  83.  

  84. /**

  85. * 邮件发送

  86. * @param string $toemail

  87. * @param string $subject

  88. * @param string $message

  89. * @return boolean

  90. */

  91. public static function sendMail($toemail = '', $subject = '', $message = '') {

  92. $mailer = Yii::createComponent ( 'application.extensions.mailer.EMailer' );

  93.  

  94. //邮件配置

  95. $mailer->SetLanguage('zh_cn');

  96. $mailer->Host = Yii::app()->params['emailHost']; //发送邮件服务器

  97. $mailer->Port = Yii::app()->params['emailPort']; //邮件端口

  98. $mailer->Timeout = Yii::app()->params['emailTimeout'];//邮件发送超时时间

  99. $mailer->ContentType = 'text/html';//设置html格式

  100. $mailer->SMTPAuth = true;

  101. $mailer->Username = Yii::app()->params['emailUserName'];

  102. $mailer->Password = Yii::app()->params['emailPassword'];

  103. $mailer->IsSMTP ();

  104. $mailer->From = $mailer->Username; // 发件人邮箱

  105. $mailer->FromName = Yii::app()->params['emailFormName']; // 发件人姓名

  106. $mailer->AddReplyTo ( $mailer->Username );

  107. $mailer->CharSet = 'UTF-8';

  108.  

  109. // 添加邮件日志

  110. $modelMail = new MailLog ();

  111. $modelMail->accept = $toemail;

  112. $modelMail->subject = $subject;

  113. $modelMail->message = $message;

  114. $modelMail->send_status = 'waiting';

  115. $modelMail->save ();

  116. // 发送邮件

  117. $mailer->AddAddress ( $toemail );

  118. $mailer->Subject = $subject;

  119. $mailer->Body = $message;

  120.  

  121. if ($mailer->Send () === true) {

  122. $modelMail->times = $modelMail->times + 1;

  123. $modelMail->send_status = 'success';

  124. $modelMail->save ();

  125. return true;

  126. } else {

  127. $error = $mailer->ErrorInfo;

  128. $modelMail->times = $modelMail->times + 1;

  129. $modelMail->send_status = 'failed';

  130. $modelMail->error = $error;

  131. $modelMail->save ();

  132. return false;

  133. }

  134. }

  135.  

  136. /**

  137. * 判断字符串是utf-8 还是gb2312

  138. * @param unknown $str

  139. * @param string $default

  140. * @return string

  141. */

  142. public static function utf8_gb2312($str, $default = 'gb2312')

  143. {

  144.    $str = preg_replace("/[x01-x7F]+/", "", $str);

  145.    if (empty($str)) return $default;

  146.  

  147.    $preg =  array(

  148.        "gb2312" => "/^([xA1-xF7][xA0-xFE])+$/", //正则判断是否是gb2312

  149.        "utf-8" => "/^[x{4E00}-x{9FA5}]+$/u",      //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了

  150.    );

  151.  

  152.    if ($default == 'gb2312') {

  153.        $option = 'utf-8';

  154.    } else {

  155.        $option = 'gb2312';

  156.    }

  157.  

  158.    if (!preg_match($preg[$default], $str)) {

  159.        return $option;

  160.    }

  161.    $str = @iconv($default, $option, $str);

  162.  

  163.    //不能转成 $option, 说明原来的不是 $default

  164.    if (empty($str)) {

  165.        return $option;

  166.    }

  167.    return $default;

  168. }

  169. /**

  170. * utf-8和gb2312自动转化

  171. * @param unknown $string

  172. * @param string $outEncoding

  173. * @return unknown|string

  174. */

  175. public static function safeEncoding($string,$outEncoding = 'UTF-8')

  176. {

  177. $encoding = "UTF-8";

  178. for($i = 0; $i < strlen ( $string ); $i ++) {

  179. if (ord ( $string {$i} ) < 128)

  180. continue;

  181.  

  182. if ((ord ( $string {$i} ) & 224) == 224) {

  183. // 第一个字节判断通过

  184. $char = $string {++ $i};

  185. if ((ord ( $char ) & 128) == 128) {

  186. // 第二个字节判断通过

  187. $char = $string {++ $i};

  188. if ((ord ( $char ) & 128) == 128) {

  189. $encoding = "UTF-8";

  190. break;

  191. }

  192. }

  193. }

  194. if ((ord ( $string {$i} ) & 192) == 192) {

  195. // 第一个字节判断通过

  196. $char = $string {++ $i};

  197. if ((ord ( $char ) & 128) == 128) {

  198. // 第二个字节判断通过

  199. $encoding = "GB2312";

  200. break;

  201. }

  202. }

  203. }

  204.  

  205. if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))

  206. return $string;

  207. else

  208. return @iconv ( $encoding, $outEncoding, $string );

  209. }

  210. /**

  211. * 返回二维数组中某个键名的所有值

  212. * @param input $array

  213. * @param string $key

  214. * @return array

  215. */

  216. public static function array_key_values($array =array(), $key='')

  217. {

  218. $ret = array();

  219. foreach((array)$array as $k=>$v){

  220. $ret[$k] = $v[$key];

  221. }

  222. return $ret;

  223. }

  224.  

  225.  

  226. /**

  227. * 判断 文件/目录 是否可写(取代系统自带的 is_writeable 函数)

  228. * @param string $file 文件/目录

  229. * @return boolean

  230. */

  231. public static function is_writeable($file) {

  232. if (is_dir($file)){

  233. $dir = $file;

  234. if ($fp = @fopen("$dir/test.txt", 'w')) {

  235. @fclose($fp);

  236. @unlink("$dir/test.txt");

  237. $writeable = 1;

  238. } else {

  239. $writeable = 0;

  240. }

  241. } else {

  242. if ($fp = @fopen($file, 'a+')) {

  243. @fclose($fp);

  244. $writeable = 1;

  245. } else {

  246. $writeable = 0;

  247. }

  248. }

  249.  

  250. return $writeable;

  251. }

  252. /**

  253. * 格式化单位

  254. */

  255. static public function byteFormat( $size, $dec = 2 ) {

  256. $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );

  257. $pos = 0;

  258. while ( $size >= 1024 ) {

  259. $size /= 1024;

  260. $pos ++;

  261. }

  262. return round( $size, $dec ) . " " . $a[$pos];

  263. }

  264.  

  265. /**

  266. * 下拉框,单选按钮 自动选择

  267. *

  268. * @param $string 输入字符

  269. * @param $param  条件

  270. * @param $type   类型

  271. * selected checked

  272. * @return string

  273. */

  274. static public function selected( $string, $param = 1, $type = 'select' ) {

  275.  

  276. $true = false;

  277. if ( is_array( $param ) ) {

  278. $true = in_array( $string, $param );

  279. }elseif ( $string == $param ) {

  280. $true = true;

  281. }

  282. $return='';

  283. if ( $true )

  284. $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';

  285.  

  286. echo $return;

  287. }

  288.  

  289. /**

  290. * 下载远程图片

  291. * @param string $url 图片的绝对url

  292. * @param string $filepath 文件的完整路径(例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名

  293. * @param string $filename 要保存的文件名(不含扩展名)

  294. * @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false

  295. */

  296. static public function downloadImage($url, $filepath, $filename) {

  297. //服务器返回的头信息

  298. $responseHeaders = array();

  299. //原始图片名

  300. $originalfilename = '';

  301. //图片的后缀名

  302. $ext = '';

  303. $ch = curl_init($url);

  304. //设置curl_exec返回的值包含Http头

  305. curl_setopt($ch, CURLOPT_HEADER, 1);

  306. //设置curl_exec返回的值包含Http内容

  307. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  308. //设置抓取跳转(http 301,302)后的页面

  309. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

  310. //设置最多的HTTP重定向的数量

  311. curl_setopt($ch, CURLOPT_MAXREDIRS, 3);

  312.  

  313. //服务器返回的数据(包括http头信息和内容)

  314. $html = curl_exec($ch);

  315. //获取此次抓取的相关信息

  316. $httpinfo = curl_getinfo($ch);

  317. curl_close($ch);

  318. if ($html !== false) {

  319. //分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串

  320. $httpArr = explode(" ", $html, 2 + $httpinfo['redirect_count']);

  321. //倒数第二段是服务器最后一次response的http头

  322. $header = $httpArr[count($httpArr) - 2];

  323. //倒数第一段是服务器最后一次response的内容

  324. $body = $httpArr[count($httpArr) - 1];

  325. $header.=" ";

  326.  

  327. //获取最后一次response的header信息

  328. preg_match_all('/([a-z0-9-_]+):s*([^ ]+) /i', $header, $matches);

  329. if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {

  330. for ($i = 0; $i < count($matches[1]); $i++) {

  331. if (array_key_exists($i, $matches[2])) {

  332. $responseHeaders[$matches[1][$i]] = $matches[2][$i];

  333. }

  334. }

  335. }

  336. //获取图片后缀名

  337. if (0 < preg_match('{(?:[^/\\]+).(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {

  338. $originalfilename = $matches[0];

  339. $ext = $matches[1];

  340. } else {

  341. if (array_key_exists('Content-Type', $responseHeaders)) {

  342. if (0 < preg_match('{image/(w+)}i', $responseHeaders['Content-Type'], $extmatches)) {

  343. $ext = $extmatches[1];

  344. }

  345. }

  346. }

  347. //保存文件

  348. if (!empty($ext)) {

  349. //如果目录不存在,则先要创建目录

  350. if(!is_dir($filepath)){

  351. mkdir($filepath, 0777, true);

  352. }

  353.  

  354. $filepath .= '/'.$filename.".$ext";

  355. $local_file = fopen($filepath, 'w');

  356. if (false !== $local_file) {

  357. if (false !== fwrite($local_file, $body)) {

  358. fclose($local_file);

  359. $sizeinfo = getimagesize($filepath);

  360. return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));

  361. }

  362. }

  363. }

  364. }

  365. return false;

  366. }

  367.  

  368.  

  369. /**

  370. * 查找ip是否在某个段位里面

  371. * @param string $ip 要查询的ip

  372. * @param $arrIP     禁止的ip

  373. * @return boolean

  374. */

  375. public static function ipAccess($ip='0.0.0.0', $arrIP = array()){

  376. $access = true;

  377. $ip && $arr_cur_ip = explode('.', $ip);

  378. foreach((array)$arrIP as $key=> $value){

  379. if($value == '*.*.*.*'){

  380. $access = false; //禁止所有

  381. break;

  382. }

  383. $tmp_arr = explode('.', $value);

  384. if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {

  385. //前两段相同

  386. if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){

  387. //第三段为* 或者相同

  388. if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){

  389. //第四段为* 或者相同

  390. $access = false; //在禁止ip列,则禁止访问

  391. break;

  392. }

  393. }

  394. }

  395. }

  396. return $access;

  397. }

  398.  

  399. /**

  400. * @param string $string 原文或者密文

  401. * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE

  402. * @param string $key 密钥

  403. * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效

  404. * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文

  405. *

  406. * @example

  407. *

  408. * $a = authcode('abc', 'ENCODE', 'key');

  409. * $b = authcode($a, 'DECODE', 'key');  // $b(abc)

  410. *

  411. * $a = authcode('abc', 'ENCODE', 'key', 3600);

  412. * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空

  413. */

  414. public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {

  415.  

  416. $ckey_length = 4;

  417. // 随机密钥长度 取值 0-32;

  418. // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。

  419. // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方

  420. // 当此值为 0 时,则不产生随机密钥

  421.  

  422.  

  423. $key = md5 ( $key ? $key : 'key' ); //这里可以填写默认key值

  424. $keya = md5 ( substr ( $key, 0, 16 ) );

  425. $keyb = md5 ( substr ( $key, 16, 16 ) );

  426. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';

  427.  

  428. $cryptkey = $keya . md5 ( $keya . $keyc );

  429. $key_length = strlen ( $cryptkey );

  430.  

  431. $string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;

  432. $string_length = strlen ( $string );

  433.  

  434. $result = '';

  435. $box = range ( 0, 255 );

  436.  

  437. $rndkey = array ();

  438. for($i = 0; $i <= 255; $i ++) {

  439. $rndkey [$i] = ord ( $cryptkey [$i % $key_length] );

  440. }

  441.  

  442. for($j = $i = 0; $i < 256; $i ++) {

  443. $j = ($j + $box [$i] + $rndkey [$i]) % 256;

  444. $tmp = $box [$i];

  445. $box [$i] = $box [$j];

  446. $box [$j] = $tmp;

  447. }

  448.  

  449. for($a = $j = $i = 0; $i < $string_length; $i ++) {

  450. $a = ($a + 1) % 256;

  451. $j = ($j + $box [$a]) % 256;

  452. $tmp = $box [$a];

  453. $box [$a] = $box [$j];

  454. $box [$j] = $tmp;

  455. $result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );

  456. }

  457.  

  458. if ($operation == 'DECODE') {

  459. if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {

  460. return substr ( $result, 26 );

  461. } else {

  462. return '';

  463. }

  464. } else {

  465. return $keyc . str_replace ( '=', '', base64_encode ( $result ) );

  466. }

  467.  

  468. }

  469.  

  470. public static function gbkToUtf8($str){

  471. return iconv("GBK", "UTF-8", $str);

  472. }

  473.  

  474. /**

  475. * 取得输入目录所包含的所有目录和文件

  476. * 以关联数组形式返回

  477. * author: flynetcn

  478. */

  479. static public function deepScanDir($dir)

  480. {

  481. $fileArr = array();

  482. $dirArr = array();

  483. $dir = rtrim($dir, '//');

  484. if(is_dir($dir)){

  485. $dirHandle = opendir($dir);

  486. while(false !== ($fileName = readdir($dirHandle))){

  487. $subFile = $dir . DIRECTORY_SEPARATOR . $fileName;

  488. if(is_file($subFile)){

  489. $fileArr[] = $subFile;

  490. } elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){

  491. $dirArr[] = $subFile;

  492. $arr = self::deepScanDir($subFile);

  493. $dirArr = array_merge($dirArr, $arr['dir']);

  494. $fileArr = array_merge($fileArr, $arr['file']);

  495. }

  496. }

  497. closedir($dirHandle);

  498. }

  499. return array('dir'=>$dirArr, 'file'=>$fileArr);

  500. }

  501.  

  502.  

  503. /**

  504. * 取得输入目录所包含的所有文件

  505. * 以数组形式返回

  506. * author: flynetcn

  507. */

  508. static public function get_dir_files($dir)

  509. {

  510. if (is_file($dir)) {

  511. return array($dir);

  512. }

  513. $files = array();

  514. if (is_dir($dir) && ($dir_p = opendir($dir))) {

  515. $ds = DIRECTORY_SEPARATOR;

  516. while (($filename = readdir($dir_p)) !== false) {

  517. if ($filename=='.' || $filename=='..') { continue; }

  518. $filetype = filetype($dir.$ds.$filename);

  519. if ($filetype == 'dir') {

  520. $files = array_merge($files, self::get_dir_files($dir.$ds.$filename));

  521. } elseif ($filetype == 'file') {

  522. $files[] = $dir.$ds.$filename;

  523. }

  524. }

  525. closedir($dir_p);

  526. }

  527. return $files;

  528. }

  529.  

  530. /**

  531. * 删除文件夹及其文件夹下所有文件

  532. */

  533. public static function deldir($dir) {

  534. //先删除目录下的文件:

  535. $dh=opendir($dir);

  536. while ($file=readdir($dh)) {

  537. if($file!="." && $file!="..") {

  538. $fullpath=$dir."/".$file;

  539. if(!is_dir($fullpath)) {

  540. unlink($fullpath);

  541. } else {

  542. self::deldir($fullpath);

  543. }

  544. }

  545. }

  546.  

  547. closedir($dh);

  548. //删除当前文件夹:

  549. if(rmdir($dir)) {

  550. return true;

  551. } else {

  552. return false;

  553. }

  554. }

  555.  

  556. /**

  557. * js 弹窗并且跳转

  558. * @param string $_info

  559. * @param string $_url

  560. * @return js

  561. */

  562. static public function alertLocation($_info, $_url) {

  563. echo "<script type='text/javascript'>alert('$_info');location.href='$_url';</script>";

  564. exit();

  565. }

  566.  

  567. /**

  568. * js 弹窗返回

  569. * @param string $_info

  570. * @return js

  571. */

  572. static public function alertBack($_info) {

  573. echo "<script type='text/javascript'>alert('$_info');history.back();</script>";

  574. exit();

  575. }

  576.  

  577. /**

  578. * 页面跳转

  579. * @param string $url

  580. * @return js

  581. */

  582. static public function headerUrl($url) {

  583. echo "<script type='text/javascript'>location.href='{$url}';</script>";

  584. exit();

  585. }

  586.  

  587. /**

  588. * 弹窗关闭

  589. * @param string $_info

  590. * @return js

  591. */

  592. static public function alertClose($_info) {

  593. echo "<script type='text/javascript'>alert('$_info');close();</script>";

  594. exit();

  595. }

  596.  

  597. /**

  598. * 弹窗

  599. * @param string $_info

  600. * @return js

  601. */

  602. static public function alert($_info) {

  603. echo "<script type='text/javascript'>alert('$_info');</script>";

  604. exit();

  605. }

  606.  

  607. /**

  608. * 系统基本参数上传图片专用

  609. * @param string $_path

  610. * @return null

  611. */

  612. static public function sysUploadImg($_path) {

  613. echo '<script type="text/javascript">document.getElementById("logo").value="'.$_path.'";</script>';

  614. echo '<script type="text/javascript">document.getElementById("pic").src="'.$_path.'";</script>';

  615. echo '<script type="text/javascript">$("#loginpop1").hide();</script>';

  616. echo '<script type="text/javascript">$("#bgloginpop2").hide();</script>';

  617. }

  618.  

  619. /**

  620. * html过滤

  621. * @param array|object $_date

  622. * @return string

  623. */

  624. static public function htmlString($_date) {

  625. if (is_array($_date)) {

  626. foreach ($_date as $_key=>$_value) {

  627. $_string[$_key] = self::htmlString($_value);  //递归

  628. }

  629. } elseif (is_object($_date)) {

  630. foreach ($_date as $_key=>$_value) {

  631. $_string->$_key = self::htmlString($_value);  //递归

  632. }

  633. } else {

  634. $_string = htmlspecialchars($_date);

  635. }

  636. return $_string;

  637. }

  638.  

  639. /**

  640. * 数据库输入过滤

  641. * @param string $_data

  642. * @return string

  643. */

  644. static public function mysqlString($_data) {

  645. $_data = trim($_data);

  646. return !GPC ? addcslashes($_data) : $_data;

  647. }

  648.  

  649. /**

  650. * 清理session

  651. */

  652. static public function unSession() {

  653. if (session_start()) {

  654. session_destroy();

  655. }

  656. }

  657.  

  658. /**

  659. * 验证是否为空

  660. * @param string $str

  661. * @param string $name

  662. * @return bool (true or false)

  663. */

  664. static function validateEmpty($str, $name) {

  665. if (empty($str)) {

  666. self::alertBack('警告:' .$name . '不能为空!');

  667. }

  668. }

  669.  

  670. /**

  671. * 验证是否相同

  672. * @param string $str1

  673. * @param string $str2

  674. * @param string $alert

  675. * @return JS

  676. */

  677. static function validateAll($str1, $str2, $alert) {

  678. if ($str1 != $str2) self::alertBack('警告:' .$alert);

  679. }

  680.  

  681. /**

  682. * 验证ID

  683. * @param Number $id

  684. * @return JS

  685. */

  686. static function validateId($id) {

  687. if (empty($id) || !is_numeric($id)) self::alertBack('警告:参数错误!');

  688. }

  689.  

  690. /**

  691. * 格式化字符串

  692. * @param string $str

  693. * @return string

  694. */

  695. static public function formatStr($str) {

  696. $arr = array(' ', ' ', '&', '@', '#', '%',  ''', '"', '\', '/', '.', ',', '$', '^', '*', '(', ')', '[', ']', '{', '}', '|', '~', '`', '?', '!', ';', ':', '-', '_', '+', '=');

  697. foreach ($arr as $v) {

  698. $str = str_replace($v, '', $str);

  699. }

  700. return $str;

  701. }

  702.  

  703. /**

  704. * 格式化时间

  705. * @param int $time 时间戳

  706. * @return string

  707. */

  708. static public function formatDate($time='default') {

  709. $date = $time == 'default' ? date('Y-m-d H:i:s', time()) : date('Y-m-d H:i:s', $time);

  710. return $date;

  711. }

  712.  

  713. /**

  714. * 获得真实IP地址

  715. * @return string

  716. */

  717. static public function realIp() {

  718. static $realip = NULL;

  719. if ($realip !== NULL) return $realip;

  720. if (isset($_SERVER)) {

  721. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {

  722. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

  723. foreach ($arr AS $ip) {

  724. $ip = trim($ip);

  725. if ($ip != 'unknown') {

  726. $realip = $ip;

  727. break;

  728. }

  729. }

  730. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {

  731. $realip = $_SERVER['HTTP_CLIENT_IP'];

  732. } else {

  733. if (isset($_SERVER['REMOTE_ADDR'])) {

  734. $realip = $_SERVER['REMOTE_ADDR'];

  735. } else {

  736. $realip = '0.0.0.0';

  737. }

  738. }

  739. } else {

  740. if (getenv('HTTP_X_FORWARDED_FOR')) {

  741. $realip = getenv('HTTP_X_FORWARDED_FOR');

  742. } elseif (getenv('HTTP_CLIENT_IP')) {

  743. $realip = getenv('HTTP_CLIENT_IP');

  744. } else {

  745. $realip = getenv('REMOTE_ADDR');

  746. }

  747. }

  748. preg_match('/[d.]{7,15}/', $realip, $onlineip);

  749. $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

  750. return $realip;

  751. }

  752.  

  753. /**

  754. * 加载 Smarty 模板

  755. * @param string $html

  756. * @return null;

  757. */

  758. static public function display() {

  759. global $tpl;$html = null;

  760. $htmlArr = explode('/', $_SERVER[SCRIPT_NAME]);

  761. $html = str_ireplace('.php', '.html', $htmlArr[count($htmlArr)-1]);

  762. $dir = dirname($_SERVER[SCRIPT_NAME]);

  763. $firstStr = substr($dir, 0, 1);

  764. $endStr = substr($dir, strlen($dir)-1, 1);

  765. if ($firstStr == '/' || $firstStr == '\') $dir = substr($dir, 1);

  766. if ($endStr != '/' || $endStr != '\') $dir = $dir . '/';

  767. $tpl->display($dir.$html);

  768. }

  769.  

  770. /**

  771. * 创建目录

  772. * @param string $dir

  773. */

  774. static public function createDir($dir) {

  775. if (!is_dir($dir)) {

  776. mkdir($dir, 0777);

  777. }

  778. }

  779.  

  780. /**

  781. * 创建文件(默认为空)

  782. * @param unknown_type $filename

  783. */

  784. static public function createFile($filename) {

  785. if (!is_file($filename)) touch($filename);

  786. }

  787.  

  788. /**

  789. * 正确获取变量

  790. * @param string $param

  791. * @param string $type

  792. * @return string

  793. */

  794. static public function getData($param, $type='post') {

  795. $type = strtolower($type);

  796. if ($type=='post') {

  797. return self::mysqlString(trim($_POST[$param]));

  798. } elseif ($type=='get') {

  799. return self::mysqlString(trim($_GET[$param]));

  800. }

  801. }

  802.  

  803. /**

  804. * 删除文件

  805. * @param string $filename

  806. */

  807. static public function delFile($filename) {

  808. if (file_exists($filename)) unlink($filename);

  809. }

  810.  

  811. /**

  812. * 删除目录

  813. * @param string $path

  814. */

  815. static public function delDir($path) {

  816. if (is_dir($path)) rmdir($path);

  817. }

  818.  

  819. /**

  820. * 删除目录及地下的全部文件

  821. * @param string $dir

  822. * @return bool

  823. */

  824. static public function delDirOfAll($dir) {

  825. //先删除目录下的文件:

  826. if (is_dir($dir)) {

  827. $dh=opendir($dir);

  828. while (!!$file=readdir($dh)) {

  829. if($file!="." && $file!="..") {

  830. $fullpath=$dir."/".$file;

  831. if(!is_dir($fullpath)) {

  832. unlink($fullpath);

  833. } else {

  834. self::delDirOfAll($fullpath);

  835. }

  836. }

  837. }

  838. closedir($dh);

  839. //删除当前文件夹:

  840. if(rmdir($dir)) {

  841. return true;

  842. } else {

  843. return false;

  844. }

  845. }

  846. }

  847.  

  848. /**

  849. * 验证登陆

  850. */

  851. static public function validateLogin() {

  852. if (empty($_SESSION['admin']['user'])) header('Location:/admin/');

  853. }

  854.  

  855. /**

  856. * 给已经存在的图片添加水印

  857. * @param string $file_path

  858. * @return bool

  859. */

  860. static public function addMark($file_path) {

  861. if (file_exists($file_path) && file_exists(MARK)) {

  862. //求出上传图片的名称后缀

  863. $ext_name = strtolower(substr($file_path, strrpos($file_path, '.'), strlen($file_path)));

  864. //$new_name='jzy_' . time() . rand(1000,9999) . $ext_name ;

  865. $store_path = ROOT_PATH . UPDIR;

  866. //求上传图片高宽

  867. $imginfo = getimagesize($file_path);

  868. $width = $imginfo[0];

  869. $height = $imginfo[1];

  870. //添加图片水印

  871. switch($ext_name) {

  872. case '.gif':

  873. $dst_im = imagecreatefromgif($file_path);

  874. break;

  875. case '.jpg':

  876. $dst_im = imagecreatefromjpeg($file_path);

  877. break;

  878. case '.png':

  879. $dst_im = imagecreatefrompng($file_path);

  880. break;

  881. }

  882. $src_im = imagecreatefrompng(MARK);

  883. //求水印图片高宽

  884. $src_imginfo = getimagesize(MARK);

  885. $src_width = $src_imginfo[0];

  886. $src_height = $src_imginfo[1];

  887. //求出水印图片的实际生成位置

  888. $src_x = $width - $src_width - 10;

  889. $src_y = $height - $src_height - 10;

  890. //新建一个真彩色图像

  891. $nimage = imagecreatetruecolor($width, $height);

  892. //拷贝上传图片到真彩图像

  893. imagecopy($nimage, $dst_im, 0, 0, 0, 0, $width, $height);

  894. //按坐标位置拷贝水印图片到真彩图像上

  895. imagecopy($nimage, $src_im, $src_x, $src_y, 0, 0, $src_width, $src_height);

  896. //分情况输出生成后的水印图片

  897. switch($ext_name) {

  898. case '.gif':

  899. imagegif($nimage, $file_path);

  900. break;

  901. case '.jpg':

  902. imagejpeg($nimage, $file_path);

  903. break;

  904. case '.png':

  905. imagepng($nimage, $file_path);

  906. break;

  907. }

  908. //释放资源

  909. imagedestroy($dst_im);

  910. imagedestroy($src_im);

  911. unset($imginfo);

  912. unset($src_imginfo);

  913. //移动生成后的图片

  914. @move_uploaded_file($file_path, ROOT_PATH.UPDIR . $file_path);

  915. }

  916. }

  917.  

  918. /**

  919. *  中文截取2,单字节截取模式

  920. * @access public

  921. * @param string $str  需要截取的字符串

  922. * @param int $slen  截取的长度

  923. * @param int $startdd  开始标记处

  924. * @return string

  925. */

  926. static public function cn_substr($str, $slen, $startdd=0){

  927. $cfg_soft_lang = PAGECHARSET;

  928. if($cfg_soft_lang=='utf-8') {

  929. return self::cn_substr_utf8($str, $slen, $startdd);

  930. }

  931. $restr = '';

  932. $c = '';

  933. $str_len = strlen($str);

  934. if($str_len < $startdd+1) {

  935. return '';

  936. }

  937. if($str_len < $startdd + $slen || $slen==0) {

  938. $slen = $str_len - $startdd;

  939. }

  940. $enddd = $startdd + $slen - 1;

  941. for($i=0;$i<$str_len;$i++) {

  942. if($startdd==0) {

  943. $restr .= $c;

  944. } elseif($i > $startdd) {

  945. $restr .= $c;

  946. }

  947. if(ord($str[$i])>0x80) {

  948. if($str_len>$i+1) {

  949. $c = $str[$i].$str[$i+1];

  950. }

  951. $i++;

  952. } else {

  953. $c = $str[$i];

  954. }

  955. if($i >= $enddd) {

  956. if(strlen($restr)+strlen($c)>$slen) {

  957. break;

  958. } else {

  959. $restr .= $c;

  960. break;

  961. }

  962. }

  963. }

  964. return $restr;

  965. }

  966.  

  967. /**

  968. *  utf-8中文截取,单字节截取模式

  969. *

  970. * @access public

  971. * @param string $str 需要截取的字符串

  972. * @param int $slen 截取的长度

  973. * @param int $startdd 开始标记处

  974. * @return string

  975. */

  976. static public function cn_substr_utf8($str, $length, $start=0) {

  977. if(strlen($str) < $start+1) {

  978. return '';

  979. }

  980. preg_match_all("/./su", $str, $ar);

  981. $str = '';

  982. $tstr = '';

  983. //为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取

  984. for($i=0; isset($ar[0][$i]); $i++) {

  985. if(strlen($tstr) < $start) {

  986. $tstr .= $ar[0][$i];

  987. } else {

  988. if(strlen($str) < $length + strlen($ar[0][$i]) ) {

  989. $str .= $ar[0][$i];

  990. } else {

  991. break;

  992. }

  993. }

  994. }

  995. return $str;

  996. }

  997.  

  998. /**

  999. * 删除图片,根据图片ID

  1000. * @param int $image_id

  1001. */

  1002. static function delPicByImageId($image_id) {

  1003. $db_name = PREFIX . 'images i';

  1004. $m = new Model();

  1005. $data = $m->getOne($db_name, "i.id={$image_id}", "i.path as p, i.big_img as b, i.small_img as s");

  1006. foreach ($data as $v) {

  1007. @self::delFile(ROOT_PATH . $v['p']);

  1008. @self::delFile(ROOT_PATH . $v['b']);

  1009. @self::delFile(ROOT_PATH . $v['s']);

  1010. }

  1011. $m->del(PREFIX . 'images', "id={$image_id}");

  1012. unset($m);

  1013. }

  1014.  

  1015. /**

  1016. * 图片等比例缩放

  1017. * @param resource $im    新建图片资源(imagecreatefromjpeg/imagecreatefrompng/imagecreatefromgif)

  1018. * @param int $maxwidth   生成图像宽

  1019. * @param int $maxheight  生成图像高

  1020. * @param string $name    生成图像名称

  1021. * @param string $filetype文件类型(.jpg/.gif/.png)

  1022. */

  1023. static public function resizeImage($im, $maxwidth, $maxheight, $name, $filetype) {

  1024. $pic_width = imagesx($im);

  1025. $pic_height = imagesy($im);

  1026. if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {

  1027. if($maxwidth && $pic_width>$maxwidth) {

  1028. $widthratio = $maxwidth/$pic_width;

  1029. $resizewidth_tag = true;

  1030. }

  1031. if($maxheight && $pic_height>$maxheight) {

  1032. $heightratio = $maxheight/$pic_height;

  1033. $resizeheight_tag = true;

  1034. }

  1035. if($resizewidth_tag && $resizeheight_tag) {

  1036. if($widthratio<$heightratio)

  1037. $ratio = $widthratio;

  1038. else

  1039. $ratio = $heightratio;

  1040. }

  1041. if($resizewidth_tag && !$resizeheight_tag)

  1042. $ratio = $widthratio;

  1043. if($resizeheight_tag && !$resizewidth_tag)

  1044. $ratio = $heightratio;

  1045. $newwidth = $pic_width * $ratio;

  1046. $newheight = $pic_height * $ratio;

  1047. if(function_exists("imagecopyresampled")) {

  1048. $newim = imagecreatetruecolor($newwidth,$newheight);

  1049. imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);

  1050. } else {

  1051. $newim = imagecreate($newwidth,$newheight);

  1052. imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);

  1053. }

  1054. $name = $name.$filetype;

  1055. imagejpeg($newim,$name);

  1056. imagedestroy($newim);

  1057. } else {

  1058. $name = $name.$filetype;

  1059. imagejpeg($im,$name);

  1060. }

  1061. }

  1062.  

  1063. /**

  1064. * 下载文件

  1065. * @param string $file_path 绝对路径

  1066. */

  1067. static public function downFile($file_path) {

  1068. //判断文件是否存在

  1069. $file_path = iconv('utf-8', 'gb2312', $file_path); //对可能出现的中文名称进行转码

  1070. if (!file_exists($file_path)) {

  1071. exit('文件不存在!');

  1072. }

  1073. $file_name = basename($file_path); //获取文件名称

  1074. $file_size = filesize($file_path); //获取文件大小

  1075. $fp = fopen($file_path, 'r'); //以只读的方式打开文件

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

  1077. header("Accept-Ranges: bytes");

  1078. header("Accept-Length: {$file_size}");

  1079. header("Content-Disposition: attachment;filename={$file_name}");

  1080. $buffer = 1024;

  1081. $file_count = 0;

  1082. //判断文件是否结束

  1083. while (!feof($fp) && ($file_size-$file_count>0)) {

  1084. $file_data = fread($fp, $buffer);

  1085. $file_count += $buffer;

  1086. echo $file_data;

  1087. }

  1088. fclose($fp); //关闭文件

  1089. }

  1090. }



 

准备开展业务? 立即创建网站 成为代理商
网络营销
  1. 企业网站如何做好网站优化与推广工作?
  2. 中小企业怎样做网络营销 广州七想网络...
  3. 网络营销并不神秘,七想网络带您揭开秘...
  4. 透过优衣库事件 看网络营销?
  5. QQ营销推广技巧?
  6. 中小企业网站如何推广才有效果呢?