• 技术文章 >php教程 >php手册

    自己项目中PHP常用工具类大全分享,php工具类大全分享

    2016-06-13 08:41:29原创391

    自己项目中PHP常用工具类大全分享,php工具类大全分享


    Php代码
    1. /**
    2. * 助手类
    3. * @author www.shouce.ren
    4. *
    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 . '//m.sbmmt.com/m/' . $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']; //发送邮件服务器
    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. // 发送邮件
    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 还是gb2312
    130. * @param unknown $str
    131. * @param string $default
    132. * @return string
    133. */
    134. public static function utf8_gb2312($str, $default = 'gb2312')
    135. {
    136. $str = preg_replace("/[\x01-\x7F]+/", "", $str);
    137. if (emptyempty($str)) return $default;
    138. $preg = array(
    139. "gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是gb2312
    140. "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u", //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
    141. );
    142. if ($default == 'gb2312') {
    143. $option = 'utf-8';
    144. } else {
    145. $option = 'gb2312';
    146. }
    147. if (!preg_match($preg[$default], $str)) {
    148. return $option;
    149. }
    150. $str = @iconv($default, $option, $str);
    151. //不能转成 $option, 说明原来的不是 $default
    152. if (emptyempty($str)) {
    153. return $option;
    154. }
    155. return $default;
    156. }
    157. /**
    158. * utf-8和gb2312自动转化
    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 = "GB2312";
    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 (!emptyempty($matches) && count($matches) == 3 && !emptyempty($matches[1]) && !emptyempty($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 (!emptyempty($ext)) {
    326. //如果目录不存在,则先要创建目录
    327. if(!is_dir($filepath)){
    328. mkdir($filepath, 0777, true);
    329. }
    330. $filepath .= '//m.sbmmt.com/m/'.$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
      声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
      专题推荐:php

    相关文章推荐

    • php批量添加数据与批量更新数据的实现方法,php添加数据• PHP之判断用户语言跳转网页• header("Location:login.php")• PHP代码:Http断点续传的实现例子• PHP5中Cookie与 Session使用详解
    1/1

    PHP中文网