首页
关于
归档
朋友
留言
API平台
告白墙
休闲游戏
更多
留言板
练字贴
Layui手册
Search
1
【PHP】PHPoffice/PHPSpreadsheet读取和写入Excel
1,006 阅读
2
【Git】No tracked branch configured for branch master or the branch doesn't exist.
742 阅读
3
【composer】composer常用命令
487 阅读
4
【Layui】控制页面元素展示隐藏
437 阅读
5
【MySQL】MySQL触发器应用场景和使用方法
417 阅读
默认分类
PHP
ThinkPHP
Laravel
面向对象
设计模式
算法
基础
网络安全
Web
HTML
CSS
JavaScript
jQuery
Layui
VUE
uni-app
Database
MySQL
Redis
RabbitMQ
Nginx
Git
Linux
Soft Ware
Windows
网赚
Go
登录
Search
标签搜索
PHP
函数
方法
类
MySQL
ThinkPHP
OOP
JavaScript
Layui
Web
Linux
Array
设计模式
Git
PHPSpreadsheet
PHPoffice
排序算法
面试题
Windows
基础
小破孩
累计撰写
212
篇文章
累计收到
16
条评论
首页
栏目
默认分类
PHP
ThinkPHP
Laravel
面向对象
设计模式
算法
基础
网络安全
Web
HTML
CSS
JavaScript
jQuery
Layui
VUE
uni-app
Database
MySQL
Redis
RabbitMQ
Nginx
Git
Linux
Soft Ware
Windows
网赚
Go
页面
关于
归档
朋友
留言
API平台
告白墙
休闲游戏
留言板
练字贴
Layui手册
搜索到
54
篇与
的结果
2022-06-23
【PHP】导入计算表格列数的两个方法对比
/** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2021/8/4 14:35 * @param string $col * @throws Exception * @Description:根据字母获取字段列长 根据列数的最大值返回最大范围内的列值 */ public function getColumnArrByMaxCol($col = ''){ if(empty($col)) throw new Exception("不能为空~"); if(strlen($col) > 2) throw new Exception("导入列数超出最大值~"); $col = strtoupper($col); $column_word = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; $colArr = []; if(in_array($col,$column_word)){ for ($i=0;$i<=25;$i++){ if($column_word[$i] == $col) { array_push($colArr,$column_word[$i]); return $colArr; } array_push($colArr,$column_word[$i]); } } $firstColumn = substr($col,0,1); $twoColumn = substr($col,1,1); if(!in_array($firstColumn,$column_word)) throw new Exception("错误的参数"); if(!in_array($twoColumn,$column_word)) throw new Exception("错误的参数"); $firstColumnNum = array_keys($column_word,$firstColumn); // $twoColumnNum = array_keys($column_word,$twoColumn); $colArr = $column_word; for($a = 0; $a <= $firstColumnNum[0]; $a++){ for($b = 0; $b <= 25; $b++){ if($twoColumn == $column_word[$b] && $firstColumnNum[0] == $a){ array_push($colArr,$column_word[$a].$column_word[$b]); return $colArr; } array_push($colArr,$column_word[$a].$column_word[$b]); } } } /** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2021/9/9 13:40 * @param string $col * @return mixed * @throws Exception * @Description:根据字母获取字段列长 根据列数的最大值返回最大范围内的列值 上面的方法在业务上有点慢,这里是重新改了一下 */ public function getColumnArrByMaxColtwo($col = ''){ if(empty($col)) throw new Exception("不能为空~"); $col= strtoupper($col); //转大写 $strLength = strlen($col); //获取长度 $column_word = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; //基础数据 $column_word_vk = array_flip($column_word); //数组kv掉换 $b = $strLength; $maxNumb = []; //验证并计算循环次数 for($strl = 0; $strl < $strLength; $strl++){ $strAloneWord = substr($col,$strl,1); if(!in_array($strAloneWord,$column_word)){ throw new Exception("错误的参数"); } $columnNumber[] = $column_word_vk[$strAloneWord]+1; $maxNum = pow(26,$b-$strl-1); $maxNumb[$strl] = $maxNum*$columnNumber[$strl]; } $totolTimes = ceil(array_sum($maxNumb)/26);//向上取整 循环次数 //数据拼接 限制在两位字母最大ZZ for($c = 0; $c < $totolTimes; $c++) { $first_word = $column_word[$c-1]; foreach($column_word as $key => $val){ if($c >= 1){ $word = $first_word.$column_word[$key]; }else{ $word = $column_word[$key]; } $column[] = $word; } } for($a = 0; $a < array_sum($maxNumb); $a++){ $new_column[] = $column[$a]; } return $new_column; }
2022年06月23日
108 阅读
0 评论
0 点赞
2022-06-23
【PHP】简单实现无限级分类
/** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2021/8/20 17:43 * @param $arr * @return array * @Description:数据树,无限级分类 */ public function getTreeByDate($arr) { $items = []; foreach($arr as $v){ $items[$v['id']] = $v; } $tree = []; foreach($items as $k => $item){ if(isset($items[$item['pid']])){ $items[$item['pid']]['child'][] = &$items[$k]; }else{ $tree[] = &$items[$k]; } } return $tree; }
2022年06月23日
86 阅读
0 评论
0 点赞
2022-06-23
【PHP】获取每个月的开始和结束的时间戳
/** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2021/6/9 10:21 * @param $year * @Description:获取任意一年的每个月的开始和结束的时间戳 */ public function getMonthBetweenTimestampByYear($year = ''){ if(empty($year)){ $year = date('Y',time()); } $month = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']; foreach($month as $key => $val){ $month_start = strtotime($year.'-'.$val);//指定月份月初时间戳 $month_end = mktime(23, 59, 59, $val+1, 00,$year);//指定月份月末时间戳 $month_s_e[] = ['start' => $month_start, 'end' => $month_end]; } return $month_s_e; }
2022年06月23日
111 阅读
0 评论
0 点赞
2022-06-23
【PHP】PHP实现创建文件目录
/** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2021/4/12 13:36 * @param $path * @Description:设置路径判断是否存在,不存在创建 */ public function createPath($path){ $Month = date('Ym',time()); $Day = date('d',time()); $path = $this->path.$Month.'/'.$Day.'/'; if(!is_dir($path)){ header("Content-type:text/html;charset=utf-8"); $res = mkdir(iconv("UTF-8", "GBK", $path),0777,true); if(!$res){ $this->createPath(); } } return $path; }
2022年06月23日
74 阅读
0 评论
0 点赞
2022-06-23
【PHP】PHP日志调试方法
/** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2021/4/2 18:01 * @param string $param 参数 * @param string $res 结果 * @param string $status 状态 false失败,true成功 * @Description:记录日志 */ public function superLog($param = '',$res = '',$status = false){ $logController = $this->request->controller(); $logName = $this->request->action(); $status = $status == true ? '成功'.PHP_EOL : '失败'.PHP_EOL; $dateTime = date('Y-m-d H:i:s',time()); $dateDay = substr($dateTime,0,10); //路径处理 $pathlog = "./fastlog/".$dateDay."/".$logController."/"; if(!is_dir($pathlog)){ header("Content-type:text/html;charset=utf-8"); $res = mkdir(iconv("UTF-8", "GBK", $pathlog),0777,true); if(!$res){ self::superLog(); } } //参数处理 if(is_array($param)){ $param = json_encode($param,JSON_UNESCAPED_UNICODE); } if(is_array($res)){ $res = json_encode($res,JSON_UNESCAPED_UNICODE); } error_log($dateTime.'=>'.$logName."\n"."参数:".$param."\n"."结果:".$res."\n".$status,3,$pathlog.$logName.'.txt'); } **便捷使用:** error_log(date('Y-m-d H:i:s',time())."=>aaa\n".print_r($data,true)."\n",3,"./aaa_log.txt");
2022年06月23日
118 阅读
0 评论
0 点赞
2022-06-23
【PHP】通过CURL获取结果集
在PHP调用别人的接口,需要用到curl相关操作,本文章集成了多个操作方法,并在今后的工作中不断完善 /** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2021/4/1 10:39 * @param string $url url地址 * @param bool $params 参数 * @param int $ispost 是否是post请求,默认get * @param int $https 是否是https,默认http * @param int $flbg 返回值是否转成数组,默认不转 * @param int $header 是否传递header值,默认不传,header值格式:$header = ['CLIENT-IP:127.0.0.1','X-FORWARDED-FOR:127.0.0.1']; * @param int $headercontent 是否获取请求的header值内容,默认不获取 * @param int $local 是否使用本地ip进行请求,默认不使用 * @return array|bool|mixed|string * @Description:curl请求 */ public function curl($url, $params = false, $ispost = 0, $https = 0, $flbg = 0, $header = 0,$headercontent = 0,$local = 0){ // $httpInfo = []; $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36'); // curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if($header){ curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } if($headercontent){ curl_setopt($ch, CURLOPT_HEADER, 1); } if($local){ $header = [ 'CLIENT-IP:127.0.0.1', 'X-FORWARDED-FOR:127.0.0.1' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } if($https){ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在 } if($ispost){ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_URL, $url); }else{ if($params){ if (is_array($params)) { $params = http_build_query($params); } curl_setopt($ch, CURLOPT_URL, $url . '?' . $params); }else{ curl_setopt($ch, CURLOPT_URL, $url); } } $response = curl_exec($ch); // if($response === FALSE){ // echo "CURL Error: " . curl_error($ch); // return false; // } // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // $httpInfo = array_merge($httpInfo, curl_getinfo($ch)); if($headercontent){ //对返回的结果进行字符串处理 if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') { $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $headers = substr($response, 0, $headerSize); $body = substr($response, $headerSize); return [$headers,$body]; //body内容是图片 } } curl_close($ch); if ($flbg) { $response = json_decode($response, true); } return $response; } 上面的用本地请求的场景是,被curl请求接口做了IP限制,如果本地不可以用,可以使用下面的方法需要一个有效的代理ip和端口号,有的还需要用户名密码,代码如下:curl_setopt($ch, CURLOPT_PROXY, "http://39.156.69.79:8080");窍门:一般情况下是不需要代理,但是伪造的ip不能用,就ping一下你扒取接口的网址,然后用这个网址的ip做伪造。百分百成功。如遇类似问题不能解决,欢迎留言讨论。
2022年06月23日
82 阅读
0 评论
0 点赞
2022-06-23
【PHP】$_SERVER详解
## $_SERVER详解 ## > 以 "http://local.sdd.com/public/index.php/fast" 这个地址为例; $_SERVER['SCRIPT_NAME']; //当前脚本的路径 /public/index.php dirname($_SERVER['SCRIPT_NAME']); //dirname() 返回路径中的目录部分 /public $_SERVER['SCRIPT_FILENAME']; //当前脚本执行的绝对路径 D:/phpstudy_pro/WWW/sdd/public/index.php $_SERVER['HTTP_HOST']; //获取当前域名 local.sdd.com $_SERVER['SERVER_NAME']; //输出配置文件httpd.conf中的ServerName,一般情况下与HTTP_HOST值相同 local.sdd.com $_SERVER['SystemRoot']; //当前服务器的操作系统的目录 C:\WINDOWS $_SERVER['SERVER_SOFTWARE']; //服务器软件配置信息 Apache/2.4.39 (Win64) OpenSSL/1.1.1b mod_fcgid/2.3.9a mod_log_rotate/1.02 $_SERVER['SERVER_PORT']; //服务器端口 80 $_SERVER['REMOTE_PORT']; //用户连接到服务器时所使用的端口 58222 $_SERVER['SERVER_ADDR']; //服务器的ip地址 127.0.0.1 $_SERVER['REMOTE_ADDR']; //浏览网页的用户ip。 127.0.0.1 $_SERVER['DOCUMENT_ROOT']; //当前运行脚本所在的根目录 D:/phpstudy_pro/WWW/sdd $_SERVER['REQUEST_SCHEME']; //服务器通信协议,是http或https。 http $_SERVER['SERVER_ADMIN']; //服务器管理员信息 admin@example.com $_SERVER['REQUEST_METHOD']; //请求数据的方式 GET $_SERVER['REQUEST_URI']; //当前脚本路径,根目录之后的目录 /public/index.php/fast $_SERVER['PHP_SELF']; //当前正在执行脚本的文件名 /public/index.php/fast $_SERVER['REQUEST_TIME']; //得到请求开始时的时间戳。 1616986524 $_SERVER['HTTP_COOKIE']; //获取浏览器的cookie信息。 authId=u%2B4BNnh9IsFDM%2BM%7C1617241258%7C7b4GM396cJIXMeM%2BS3v0tszZx%2FKx; shownum=10 $_SERVER['HTTP_CONNECTION']; //当前请求的连接情况 close $_SERVER['HTTP_USER_AGENT']; //获取用户相关信息,包括用户浏览器、操作系统等信息 Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 $_SERVER['HTTP_ACCEPT']; //当前请求的ACCEPT头部信息 text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 $_SERVER['HTTP_ACCEPT_LANGUAGE']; //返回用户默认的语言设置,后面的q值表示用户对该语言的喜好程度 zh-CN,zh;q=0.9
2022年06月23日
121 阅读
0 评论
0 点赞
2022-06-23
【PHP】民族数组
["汉族","蒙古族","回族","藏族","维吾尔族","苗族","彝族","壮族","布依族","朝鲜族","满族","侗族","瑶族","白族","土家族", "哈尼族","哈萨克族","傣族","黎族","傈僳族","佤族","畲族","高山族","拉祜族","水族","东乡族","纳西族","景颇族","柯尔克孜族", "土族","达斡尔族","仫佬族","羌族","布朗族","撒拉族","毛南族","仡佬族","锡伯族","阿昌族","普米族","塔吉克族","怒族", "乌孜别克族", "俄罗斯族","鄂温克族","德昂族","保安族","裕固族","京族","塔塔尔族","独龙族","鄂伦春族","赫哲族","门巴族","珞巴族","基诺族"];
2022年06月23日
117 阅读
0 评论
0 点赞
2022-06-21
【PHP】根据身份证号码获取 性别,年龄,出生日期 的信息
//18位身份证取性别,倒数第二位奇数是男,偶数是女; $sex = substr($idcard, (strlen($idcard)==18 ? -2 : -1), 1) % 2 ? '1' : '2'; //取身份证年月日; $birthday = strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8); //身份证年月日转换成时间戳 $birthdays = strtotime(strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8)); //取当天日期; $today = strtotime('today'); //用时间戳相减算出年龄; $diff = floor(($today-$birthdays)/86400/365); //取出年龄值; $age = strtotime(substr($idcard,6,8).'+'.$diff.'years')>$today?($diff+1):$diff;
2022年06月21日
332 阅读
0 评论
0 点赞
2022-06-21
【PHP】PHP导出Excel所需要的表头上方的字母超过26位的解决方法
/** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2020/12/23 16:08 * @param int $column_num * @return mixed * @Description:获取表格列数的字母 */ public function getMaxColumn(int $column_num) { try{ if(empty($column_num)){ throw new Exception('column_num:列数为空~'); } if(!is_int($column_num)){ throw new Exception('column_num:参数类型错误~'); } if($column_num > 26*26 || $column_num < 0){ throw new Exception('最大列数:676列,最小列数:1列'); } $column_word = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; //生成循环次数 $num = ceil($column_num/26); for($c = 0; $c < $num; $c++) { $first_word = $column_word[$c-1]; foreach($column_word as $key => $val){ if($c >= 1){ $word = $first_word.$column_word[$key]; }else{ $word = $column_word[$key]; } $column[] = $word; } } for($a = 0; $a < $column_num; $a++){ $new_column[] = $column[$a]; } return $new_column; }catch (Exception $e){ returnResponse(100,$e->getMessage()); } }
2022年06月21日
140 阅读
0 评论
0 点赞
2022-06-21
【PHP】PHP获取数组中重复value的key值
/** * @Author:小破孩 * @Time: 2020/8/7 17:14 * @param $array * @return array * @Description:获取数组重复value的key值 */ function getKeyByArrayValue($array){ $keyarr= []; $resultkey = []; foreach ($array as $k => $v) { if (in_array($v, $keyarr)) { //在数组中搜索键值$v,并返回它的键名 $resultkey[] = array_search($v,$keyarr); $resultkey[] = $k; }else{ $keyarr[] = $v; } } return $resultkey; }
2022年06月21日
122 阅读
0 评论
0 点赞
2022-06-21
【PHP】PHP实现网页转PDF - MPDF扩展
**PHP版本和扩展** mPDF >=7.0支持PHP^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0 PHP 7.3支持,因为mPDF v7.1.7 PHP 7.4支持,因为mPDF v8.0.4 PHPmbstring和gd必须加载扩展程序。 > 一些高级功能可能需要额外的扩展,例如zlib对于输出和嵌入式资源(如字体)的压缩,bcmath用于生成条形码或xml用于字符集转换和SVG处理。 **安装** composer require mpdf/mpdf **使用:** /** * @Author:小破孩 * @Time: 2020/8/10 19:04 * @param $url 网页地址 * @param $hetongming pdf存表的原名 * @return mixed|string * @throws \Mpdf\MpdfException * @Description:网页转PDF */ function htmlTopdf($url,$hetongming){ $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8','format'=>'A4','useSubstitutions'=>true,'useAdobeCJK'=>true,'autoScriptToLang'=>true,'autoLangToFont'=>true,'mgl'=>15,'mgr'=>15,'mgt'=>16,'mgb'=>16,'mgh'=>9,'mgf'=>9, 'orientation'=>'P']); $page = file_get_contents($url); $pwd = 'PDF_TY'.setCode();//修改文档的密码 // $pwds = setPwd($pwd); //查看密码 $mpdf->SetProtection(array(),'',$pwd,128); $mpdf->WriteHTML($page); $pdf_name = setNumber(); $name = "./Uploads/pdf/".$pdf_name.".pdf"; $mpdf->Output( $name ,'F'); $urls = "/Uploads/pdf/".$pdf_name.".pdf"; $pdf_filesize = filesize($name); $img_number = savePdf($hetongming,$pwd,$pdf_filesize,$urls); return $img_number; } 参考资料: > github:https://github.com/mpdf/mpdf > manual:https://mpdf.github.io/
2022年06月21日
118 阅读
0 评论
0 点赞
2022-06-21
【PHP】PHP生成随机 数,字符串
/** * @Author:小破孩 * @Time: 2020/7/15 17:39 * @param string $length 默认10 * @return string * @Description:生成数字和字母混合的邀请码 */ function setCode($length='10'){ $key=''; $pattern = ['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; for($i=0;$i<$length;$i++) { $key .= $pattern[mt_rand(0,35)]; //生成php随机数 } return $key; } // 生成随机字符串 private function randomString($len = 32) { $string = ''; $char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; for ($i = 0; $i < $len; $i++) { $string .= $char[mt_rand(0, strlen($char) - 1)]; } return $string; } const MINIWORD = ['a','b','c','d','e','f','g','h','k','m','n','p','q','r','t','w','x','y','z'];//'l',,'i','j','s','o','u','v' const NUMS = ['2', '3', '5', '6', '7', '8', '9'];//'4', '1','0', /** * Author: 小破孩 * Email: 3584685883@qq.com * Time: 2021/12/29 10:26 * @param int $length * @return string * Description:核销码 */ public function setVerificationCode(int $length = 4):string { $dictionary =array_merge(self::MINIWORD,self::NUMS); shuffle($dictionary); $codeArrKey = array_rand($dictionary,$length); $code = ''; for($i = 0; $i < count($codeArrKey); $i++){ $code .= $dictionary[$i]; } return $code; } /** * Author: 小破孩 * Email: 3584685883@qq.com * Time: 2021/12/29 10:16 * @param int $length default 6 * @return int * Description:设置验证码 */ public function setSmsCode(int $length = 6):int { if($length == 6){ return mt_rand(100000,999999); } return mt_rand(1000,9999); }
2022年06月21日
97 阅读
0 评论
0 点赞
2022-06-21
【PHP】PHPMailer发送邮件
/** * @Author:小破孩 * @Time: 2020/7/10 13:13 * @param $title 邮件标题 * @param $content 内容 * @param $toemail 收件人邮箱 * @Description:发送邮件 */ function sendEmail($title, $content, $toemail, $usernumber, $type){ try{ $mail = new \PHPMailer\PHPMailer\PHPMailer(); $mail->isSMTP();// 使用SMTP服务 $mail->CharSet = "utf8";// 编码格式为utf8,不设置编码的话,中文会出现乱码 $mail->Host = "smtp.163.com";// 发送方的SMTP服务器地址 $mail->SMTPAuth = true;// 是否使用身份验证 $mail->Username = Config('app.email_name');// 发送方的163邮箱用户名,就是你申请163的SMTP服务使用的163邮箱 $mail->Password = Config('app.email_allow');// 发送方的邮箱密码,注意用163邮箱这里填写的是“客户端授权密码”而不是邮箱的登录密码! $mail->SMTPSecure = "ssl";// 使用ssl协议方式 $mail->Port = config('app.email_port');// 163邮箱的ssl协议方式端口号是465/994 $mail->setFrom(config('app.email_address'),config('app.email_sendpeopleinfo'));// 设置发件人信息,如邮件格式说明中的发件人,这里会显示为Mailer(xxxx@163.com),Mailer是当做名字显示 $mail->addAddress($toemail,'小破孩回复消息');// 设置收件人信息,如邮件格式说明中的收件人,这里会显示为Liang(yyyy@163.com) $mail->addReplyTo(config('app.email_receive'),'小破孩');// 设置回复人信息,指的是收件人收到邮件后,如果要回复,回复邮件将发送到的邮箱地址 $mail->Subject = $title;// 邮件标题 $mail->Body = $content/*."点击可以查看文章地址:".$desc_url*/;// 邮件正文 if(!$mail->send()){// 发送邮件 returnResponse(100,$mail->ErrorInfo);// 输出错误信息 echo "Mailer Error: ".$mail->ErrorInfo; } //信息入库 $data['e_user_number'] = $usernumber; $data['e_title'] = $title; $data['e_content'] = $content; $data['e_emali_receive'] = $toemail; $data['e_type'] = $type; $res = Db::name('email')->insert($data); if($res){ return $res; } }catch (\Exception $e){ returnResponse(100,$e->getMessage()); } }
2022年06月21日
92 阅读
0 评论
0 点赞
2022-06-21
【PHP】生成avatar头像
/** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2020/12/10 20:00 * @param string $email 邮箱 * @param int $s 大小 * @param string $d * @param string $g * @return string * @Description:生成avatar头像 */ function getAvatar($email='', $s=40, $d='mm', $g='g') { $hash = md5($email); $avatar = "http://www.gravatar.com/avatar/$hash?s=$s&d=$d&r=$g"; return $avatar; }
2022年06月21日
96 阅读
0 评论
0 点赞
2022-06-21
【PHP】获取文件MIME类型-根据文件扩展名来获取
function getFileType($ext){ static $mime_types = [ 'apk' => 'application/vnd.android.package-archive', '3gp' => 'video/3gpp', 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'asc' => 'text/plain', 'atom' => 'application/atom+xml', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/octet-stream', 'bmp' => 'image/bmp', 'cdf' => 'application/x-netcdf', 'cgm' => 'image/cgm', 'class' => 'application/octet-stream', 'cpio' => 'application/x-cpio', 'cpt' => 'application/mac-compactpro', 'csh' => 'application/x-csh', 'css' => 'text/css', 'dcr' => 'application/x-director', 'dif' => 'video/x-dv', 'dir' => 'application/x-director', 'djv' => 'image/vnd.djvu', 'djvu' => 'image/vnd.djvu', 'dll' => 'application/octet-stream', 'dmg' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'doc' => 'application/msword', 'dtd' => 'application/xml-dtd', 'dv' => 'video/x-dv', 'dvi' => 'application/x-dvi', 'dxr' => 'application/x-director', 'eps' => 'application/postscript', 'etx' => 'text/x-setext', 'exe' => 'application/octet-stream', 'ez' => 'application/andrew-inset', 'flv' => 'video/x-flv', 'gif' => 'image/gif', 'gram' => 'application/srgs', 'grxml' => 'application/srgs+xml', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'hdf' => 'application/x-hdf', 'hqx' => 'application/mac-binhex40', 'htm' => 'text/html', 'html' => 'text/html', 'ice' => 'x-conference/x-cooltalk', 'ico' => 'image/x-icon', 'ics' => 'text/calendar', 'ief' => 'image/ief', 'ifb' => 'text/calendar', 'iges' => 'model/iges', 'igs' => 'model/iges', 'jnlp' => 'application/x-java-jnlp-file', 'jp2' => 'image/jp2', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'js' => 'application/x-javascript', 'kar' => 'audio/midi', 'latex' => 'application/x-latex', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'm3u' => 'audio/x-mpegurl', 'm4a' => 'audio/mp4a-latm', 'm4p' => 'audio/mp4a-latm', 'm4u' => 'video/vnd.mpegurl', 'm4v' => 'video/x-m4v', 'mac' => 'image/x-macpaint', 'man' => 'application/x-troff-man', 'mathml' => 'application/mathml+xml', 'me' => 'application/x-troff-me', 'mesh' => 'model/mesh', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mif' => 'application/vnd.mif', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpga' => 'audio/mpeg', 'ms' => 'application/x-troff-ms', 'msh' => 'model/mesh', 'mxu' => 'video/vnd.mpegurl', 'nc' => 'application/x-netcdf', 'oda' => 'application/oda', 'ogg' => 'application/ogg', 'ogv' => 'video/ogv', 'pbm' => 'image/x-portable-bitmap', 'pct' => 'image/pict', 'pdb' => 'chemical/x-pdb', 'pdf' => 'application/pdf', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'pic' => 'image/pict', 'pict' => 'image/pict', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'pnt' => 'image/x-macpaint', 'pntg' => 'image/x-macpaint', 'ppm' => 'image/x-portable-pixmap', 'ppt' => 'application/vnd.ms-powerpoint', 'ps' => 'application/postscript', 'qt' => 'video/quicktime', 'qti' => 'image/x-quicktime', 'qtif' => 'image/x-quicktime', 'ra' => 'audio/x-pn-realaudio', 'ram' => 'audio/x-pn-realaudio', 'ras' => 'image/x-cmu-raster', 'rdf' => 'application/rdf+xml', 'rgb' => 'image/x-rgb', 'rm' => 'application/vnd.rn-realmedia', 'roff' => 'application/x-troff', 'rtf' => 'text/rtf', 'rtx' => 'text/richtext', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'silo' => 'model/mesh', 'sit' => 'application/x-stuffit', 'skd' => 'application/x-koan', 'skm' => 'application/x-koan', 'skp' => 'application/x-koan', 'skt' => 'application/x-koan', 'smi' => 'application/smil', 'smil' => 'application/smil', 'snd' => 'audio/basic', 'so' => 'application/octet-stream', 'spl' => 'application/x-futuresplash', 'src' => 'application/x-wais-source', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'svg' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash', 't' => 'application/x-troff', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tr' => 'application/x-troff', 'tsv' => 'text/tab-separated-values', 'txt' => 'text/plain', 'ustar' => 'application/x-ustar', 'vcd' => 'application/x-cdlink', 'vrml' => 'model/vrml', 'vxml' => 'application/voicexml+xml', 'wav' => 'audio/x-wav', 'wbmp' => 'image/vnd.wap.wbmp', 'wbxml' => 'application/vnd.wap.wbxml', 'webm' => 'video/webm', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wrl' => 'model/vrml', 'xbm' => 'image/x-xbitmap', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xls' => 'application/vnd.ms-excel', 'xml' => 'application/xml', 'xpm' => 'image/x-xpixmap', 'xsl' => 'application/xml', 'xslt' => 'application/xslt+xml', 'xul' => 'application/vnd.mozilla.xul+xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'zip' => 'application/zip' ]; return isset($mime_types[$ext]) ? $mime_types[$ext] : 'application/octet-stream'; }
2022年06月21日
125 阅读
0 评论
0 点赞
2022-06-19
【PHP】PHP实现驼峰转下划线
function to_slash($array) { // 先转成json字符串,进行正则替换,再转换为数组 $tmp = json_encode($array); $tmp = strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $tmp)); $tmp = json_decode($tmp, true); return $tmp; } 原理: // 驼峰转下划线 // 先添加分隔符,再转成小写 // userId => user_id $str = preg_replace('/((?<=[a-z])(?=[A-Z]))/','_',$str); $str = strtolower($str); // 下划线转驼峰 // 同样先添加分隔符,再转成大写 // user_id => userId $array = explode('_',$str); array_walk($array,create_function('&$v','$v=ucwords($v);')); $str = implode('',$array); // 首字母转小写 $str{0} = strtolower($str{0})
2022年06月19日
67 阅读
0 评论
0 点赞
2022-06-19
【PHP】PHP地理位置计算
<?php /** *求两个已知经纬度之间的距离,单位为米 *@param lng1,lng2 经度 *@param lat1,lat2 纬度 *@return float 距离,单位米 **/ function getdistance($lng1,$lat1,$lng2,$lat2){ //将角度转为狐度 $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度 $radLat2=deg2rad($lat2); $radLng1=deg2rad($lng1); $radLng2=deg2rad($lng2); $a=$radLat1-$radLat2; $b=$radLng1-$radLng2; $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000; return intval($s); } function distanceConvert($s){ $s = intval($s); if($s <= 0){ return '附近'; }elseif($s > 0 && $s <= 1000){ return $s.'m'; }elseif($s > 1000 && $s <= 2000){ return '<2km'; }elseif($s > 2000 && $s <= 3000){ return '<3km'; }elseif($s > 3000 && $s <= 4000){ return '<4km'; }elseif($s > 4000 && $s <= 5000){ return '<5km'; }elseif($s > 5000){ return '>5km'; } } /** * 根据条件获取商户列表 * @param string $lng * @param string $lat * @param string $city_id * @param string $district_id * @param string $type_id * @param string $search * @return mixed */ //如果存在经纬度则考虑范围5公里内数据,如果不存在经纬度,则不考虑 public function GetShopList($navigationId = 0,$page = 1,$size =10 ,$lng = '', $lat ='', $city_id = '',$district_id = '',$type_id = '',$search = '') { $field = 'id,province_id,city_id,district_id,navigation_id,type_id,name,phone,address,logo,stime,etime,rule,activity,discount,latitude,longitude,status,token,sort,description,gmt_created'; $where = array( 'is_deleted' => 0, 'is_show' => 1, 'navigation_id'=>$navigationId, ); //判断城市,县区,分类是否存在 if(!empty($city_id)){ $where['city_id|province_id'] = $city_id; } if(!empty($district_id)){ $where['district_id'] = $district_id; } if(!empty($type_id)){ $where['type_id'] = $type_id; } if(!empty($search)){ $where['name'] = array('like',"%{$search}%"); } $offset = ($page * $size) - ($size - 1); //如果存在经纬度,就根据经纬度查询5公里范围内数据 if(!empty($lng) && !empty($lat)) { // //求出半径 // $radius = 5;//半径范围,单位km // $rangeLat = 180 / pi() * $radius / 6372.797;//纬度范围 // $rangeLng = $rangeLat / cos($lat * pi() / 180.0); //经度范围 // $maxLat = $lat + $rangeLat; //x1 // $minLat = $lat - $rangeLat; //x0 // $maxLng = $lng + $rangeLng; //y1 // $minLng = $lng - $rangeLng; //y0 // // $where['latitude'] = array(array('lt',$maxLat),array('gt',$minLat)); // $where['longitude'] = array(array('lt',$maxLng),array('gt',$minLng)); $list = $this->where($where)->field($field)->order("abs(longitude - {$lng}) + abs(latitude - {$lat})")->limit($offset,$size)->select(); }else{ $list = $this->where($where)->field($field)->order('sort asc')->limit($offset,$size)->select(); } //记录错误日志 if ($list === false) { wLog('GetShopList error! sql:' . $this->getLastSql(), $this->errorFile); wLog('GetShopList error! errorInfo:' . $this->error, $this->errorFile); } //wLog('GetShopList sql:' . $this->getLastSql(), $this->errorFile); return $list; }
2022年06月19日
81 阅读
0 评论
0 点赞
2022-06-19
【PHP】PHP原生生成EXCEL
<?php /*** * 生成excle文件 ***/ $time = time(); $filename = date("Y年m月d日h点m分s秒", $time).'问卷数据'; $rows = Sp_Looks_Vote::downvote(); $file = $filename.".csv"; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); $tabletitle .= "购买地址,常常购买,喜欢模特,内容如何,印象如何,是否购买,感觉如何,购买方式,购买方式建议,吸引点,改进建议"; $conter = iconv('utf-8','gbk',$tabletitle)."\n"; echo $conter;die; /*** * 生成word文件 ***/ header("Content-Type: application/msword"); header("Content-Disposition: attachment; filename=doc.doc"); header("Pragma: no-cache"); header("Expires: 0"); $output = '<table border="1" cellspacing="2" cellpadding="2" width="90%" align="center">'; $output .= '<tr bgcolor="#cccccc"><td align="center">图片</td></tr>'; $output .= '<tr bgcolor="#f6f7fa"><td><span style="color:#FF0000;"><strong>下面是一张图片</strong></span& gt;</td></tr>'; $output .= '<tr><td align="center"><img src="http://zi.csdn.net/48260_2.gif"></td></tr>'; $output .= '</table>'; echo $output; ?>
2022年06月19日
130 阅读
0 评论
0 点赞
2022-06-19
【PHP】PHP的邮件发送类
<?php /** * 邮件发送类 * 支持发送纯文本邮件和HTML格式的邮件,可以多收件人,多抄送,多秘密抄送,带附件的邮件 * 需要的php扩展,sockets和Fileinfo。 * @example * $mail = new MySendMail(); * $mail->setServer("XXXXX", "XXXXX@XXXXX", "XXXXX"); 设置smtp服务器 * $mail->setFrom("XXXXX"); 设置发件人 * $mail->setReceiver("XXXXX"); 设置收件人,多个收件人,调用多次 * $mail->setCc("XXXX"); 设置抄送,多个抄送,调用多次 * $mail->setBcc("XXXXX"); 设置秘密抄送,多个秘密抄送,调用多次 * $mail->setMailInfo("test", "<b>test</b>"); 设置邮件主题、内容 * $mail->sendMail(); 发送 */ class MySendMail { /** * @var string 邮件传输代理用户名 * @access private */ private $_userName; /** * @var string 邮件传输代理密码 * @access private */ private $_password; /** * @var string 邮件传输代理服务器地址 * @access protected */ protected $_sendServer; /** * @var int 邮件传输代理服务器端口 * @access protected */ protected $_port=25; /** * @var string 发件人 * @access protected */ protected $_from; /** * @var string 收件人 * @access protected */ protected $_to; /** * @var string 抄送 * @access protected */ protected $_cc; /** * @var string 秘密抄送 * @access protected */ protected $_bcc; /** * @var string 主题 * @access protected */ protected $_subject; /** * @var string 邮件正文 * @access protected */ protected $_body; /** * @var string 附件 * @access protected */ protected $_attachment; /** * @var reource socket资源 * @access protected */ protected $_socket; /** * @var string 错误信息 * @access protected */ protected $_errorMessage; /** * 设置邮件传输代理,如果是可以匿名发送有邮件的服务器,只需传递代理服务器地址就行 * @access public * @param string $server 代理服务器的ip或者域名 * @param string $username 认证账号 * @param string $password 认证密码 * @param int $port 代理服务器的端口,smtp默认25号端口 * @return boolean */ public function setServer($server, $username="", $password="", $port=25) { $this->_sendServer = $server; $this->_port = $port; if(!empty($username)) { $this->_userName = base64_encode($username); } if(!empty($password)) { $this->_password = base64_encode($password); } return true; } /** * 设置发件人 * @access public * @param string $from 发件人地址 * @return boolean */ public function setFrom($from) { $this->_from = $from; return true; } /** * 设置收件人,多个收件人,连续调用多次. * @access public * @param string $to 收件人地址 * @return boolean */ public function setReceiver($to) { if(isset($this->_to)) { if(is_string($this->_to)) { $this->_to = array($this->_to); $this->_to[] = $to; return true; } elseif(is_array($this->_to)) { $this->_to[] = $to; return true; } else { return false; } } else { $this->_to = $to; return true; } } /** * 设置抄送,多个抄送,连续调用多次. * @access public * @param string $cc 抄送地址 * @return boolean */ public function setCc($cc) { if(isset($this->_cc)) { if(is_string($this->_cc)) { $this->_cc = array($this->_cc); $this->_cc[] = $cc; return true; } elseif(is_array($this->_cc)) { $this->_cc[] = $cc; return true; } else { return false; } } else { $this->_cc = $cc; return true; } } /** * 设置秘密抄送,多个秘密抄送,连续调用多次 * @access public * @param string $bcc 秘密抄送地址 * @return boolean */ public function setBcc($bcc) { if(isset($this->_bcc)) { if(is_string($this->_bcc)) { $this->_bcc = array($this->_bcc); $this->_bcc[] = $bcc; return true; } elseif(is_array($this->_bcc)) { $this->_bcc[] = $bcc; return true; } else { return false; } } else { $this->_bcc = $bcc; return true; } } /** * 设置邮件信息 * @access public * @param string $body 邮件主题 * @param string $subject 邮件主体内容,可以是纯文本,也可是是HTML文本 * @param string $attachment 附件,文件地址 * @return boolean */ public function setMailInfo($subject, $body, $attachment="") { $this->_subject = $subject; $this->_body = base64_encode($body); if(!empty($attachment)) { $this->_attachment = $attachment; } return true; } /** * 发送邮件 * @access public * @return boolean */ public function sendMail() { $command = $this->getCommand(); $this->socket(); foreach ($command as $value) { if($this->sendCommand($value[0], $value[1])) { continue; } else{ return false; } } //其实这里也没必要关闭,smtp命令:QUIT发出之后,服务器就关闭了连接,本地的socket资源会自动释放 $this->close(); echo 'Mail OK!'; return true; } /** * 返回错误信息 * @return string */ public function error(){ if(!isset($this->_errorMessage)) { $this->_errorMessage = ""; } return $this->_errorMessage; } /** * 返回mail命令 * @access protected * @return array */ protected function getCommand() { $command = array( array("HELO sendmail\r\n", 250) ); if(!empty($this->_userName)){ $command[] = array("AUTH LOGIN\r\n", 334); $command[] = array($this->_userName . "\r\n", 334); $command[] = array($this->_password . "\r\n", 235); } $command[] = array("MAIL FROM:<" . $this->_from . ">\r\n", 250); $separator = "----=_Part_" . md5($this->_from . time()) . uniqid(); //分隔符 //设置发件人 $header = "FROM: test<" . $this->_from . ">\r\n"; //设置收件人 if(is_array($this->_to)) { $count = count($this->_to); for($i=0; $i<$count; $i++){ $command[] = array("RCPT TO: <" . $this->_to[$i] . ">\r\n", 250); if($i == 0){ $header .= "TO: <" . $this->_to[$i] .">"; } elseif($i + 1 == $count){ $header .= ",<" . $this->_to[$i] .">\r\n"; } else{ $header .= ",<" . $this->_to[$i] .">"; } } } else{ $command[] = array("RCPT TO: <" . $this->_to . ">\r\n", 250); $header .= "TO: <" . $this->_to . ">\r\n"; } //设置抄送 if(isset($this->_cc)) { if(is_array($this->_cc)) { $count = count($this->_cc); for($i=0; $i<$count; $i++){ $command[] = array("RCPT TO: <" . $this->_cc[$i] . ">\r\n", 250); if($i == 0){ $header .= "CC: <" . $this->_cc[$i] .">"; } elseif($i + 1 == $count){ $header .= ",<" . $this->_cc[$i] .">\r\n"; } else{ $header .= ",<" . $this->_cc[$i] .">"; } } } else{ $command[] = array("RCPT TO: <" . $this->_cc . ">\r\n", 250); $header .= "CC: <" . $this->_cc . ">\r\n"; } } //设置秘密抄送 if(isset($this->_bcc)) { if(is_array($this->_bcc)) { $count = count($this->_bcc); for($i=0; $i<$count; $i++){ $command[] = array("RCPT TO: <" . $this->_bcc[$i] . ">\r\n", 250); if($i == 0){ $header .= "BCC: <" . $this->_bcc[$i] .">"; } elseif($i + 1 == $count){ $header .= ",<" . $this->_bcc[$i] .">\r\n"; } else{ $header .= ",<" . $this->_bcc[$i] .">"; } } } else{ $command[] = array("RCPT TO: <" . $this->_bcc . ">\r\n", 250); $header .= "BCC: <" . $this->_bcc . ">\r\n"; } } $header .= "Subject: " . $this->_subject ."\r\n"; if(isset($this->_attachment)) { //含有附件的邮件头需要声明成这个 $header .= "Content-Type: multipart/mixed;\r\n"; } elseif(false){ //邮件体含有图片资源的需要声明成这个 $header .= "Content-Type: multipart/related;\r\n"; } else{ //html或者纯文本的邮件声明成这个 $header .= "Content-Type: multipart/alternative;\r\n"; } //邮件头分隔符 $header .= "\t" . 'boundary="' . $separator . '"'; $header .= "\r\nMIME-Version: 1.0\r\n"; $header .= "\r\n--" . $separator . "\r\n"; $header .= "Content-Type:text/html; charset=utf-8\r\n"; $header .= "Content-Transfer-Encoding: base64\r\n\r\n"; $header .= $this->_body . "\r\n"; $header .= "--" . $separator . "\r\n"; //加入附件 if(isset($this->_attachment)){ $header .= "\r\n--" . $separator . "\r\n"; $header .= "Content-Type: " . $this->getMIMEType() . '; name="' . basename($this->_attachment) . '"' . "\r\n"; $header .= "Content-Transfer-Encoding: base64\r\n"; $header .= 'Content-Disposition: attachment; filename="' . basename($this->_attachment) . '"' . "\r\n"; $header .= "\r\n"; $header .= $this->readFile(); $header .= "\r\n--" . $separator . "\r\n"; } $header .= "\r\n.\r\n"; $command[] = array("DATA\r\n", 354); $command[] = array($header, 250); $command[] = array("QUIT\r\n", 221); return $command; } /** * 发送命令 * @access protected * @param string $command 发送到服务器的smtp命令 * @param int $code 期望服务器返回的响应吗 * @return boolean */ protected function sendCommand($command, $code) { echo 'Send command:' . $command . ',expected code:' . $code . '<br />'; //发送命令给服务器 try{ if(socket_write($this->_socket, $command, strlen($command))){ //当邮件内容分多次发送时,没有$code,服务器没有返回 if(empty($code)) { return true; } //读取服务器返回 $data = trim(socket_read($this->_socket, 1024)); echo 'response:' . $data . '<br /><br />'; if($data) { $pattern = "/^".$code."/"; if(preg_match($pattern, $data)) { return true; } else{ $this->_errorMessage = "Error:" . $data . "|**| command:"; return false; } } else{ $this->_errorMessage = "Error:" . socket_strerror(socket_last_error()); return false; } } else{ $this->_errorMessage = "Error:" . socket_strerror(socket_last_error()); return false; } }catch(Exception $e) { $this->_errorMessage = "Error:" . $e->getMessage(); } } /** * 读取附件文件内容,返回base64编码后的文件内容 * @access protected * @return mixed */ protected function readFile() { if(isset($this->_attachment) && file_exists($this->_attachment)) { $file = file_get_contents($this->_attachment); return base64_encode($file); } else { return false; } } /** * 获取附件MIME类型 * @access protected * @return mixed */ protected function getMIMEType() { if(isset($this->_attachment) && file_exists($this->_attachment)) { $mime = mime_content_type($this->_attachment); if(! preg_match("/gif|jpg|png|jpeg/", $mime)){ $mime = "application/octet-stream"; } return $mime; } else { return false; } } /** * 建立到服务器的网络连接 * @access private * @return boolean */ private function socket() { if(!function_exists("socket_create")) { $this->_errorMessage = "Extension sockets must be enabled"; return false; } //创建socket资源 $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); if(!$this->_socket) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } socket_set_block($this->_socket);//设置阻塞模式 //连接服务器 if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } socket_read($this->_socket, 1024); return true; } /** * 关闭socket * @access private * @return boolean */ private function close() { if(isset($this->_socket) && is_object($this->_socket)) { $this->_socket->close(); return true; } $this->_errorMessage = "No resource can to be close"; return false; } } <?php /** * 邮件发送类 * 仅支持发送纯文本和HTML内容邮件 * 需要的php扩展,sockets * @example * $mail = new MySendMail(); * $mail->setServer("XXXXX", "XXXXX@XXXXX", "XXXXX"); 设置smtp服务器 * $mail->setFrom("XXXXX"); 设置发件人 * $mail->setReceiver("XXXXX"); 设置收件人 * $mail->setMailInfo("test", "<b>test</b>"); 设置邮件主题、内容 * $mail->sendMail(); 发送 */ class MySendMail2 { /** * @var string 邮件传输代理用户名 * @access private */ private $_userName; /** * @var string 邮件传输代理密码 * @access private */ private $_password; /** * @var string 邮件传输代理服务器地址 * @access private */ private $_sendServer; /** * @var int 邮件传输代理服务器端口 * @access protected */ protected $_port=25; /** * @var string 发件人 * @access protected */ protected $_from; /** * @var string 收件人 * @access protected */ protected $_to; /** * @var string 主题 * @access protected */ protected $_subject; /** * @var string 邮件正文 * @access protected */ protected $_body; /** * @var reource socket资源 * @access protected */ protected $_socket; /** * @var string 错误信息 * @access protected */ protected $_errorMessage; /** * 设置邮件传输代理,如果是可以匿名发送有邮件的服务器,只需传递代理服务器地址就行 * @access public * @param string $server 代理服务器的ip或者域名 * @param string $username 认证账号 * @param string $password 认证密码 * @param int $port 代理服务器的端口,smtp默认25号端口 * @return boolean */ public function setServer($server, $username="", $password="", $port=25) { $this->_sendServer = $server; $this->_port = $port; if(!empty($username)) { $this->_userName = base64_encode($username); } if(!empty($password)) { $this->_password = base64_encode($password); } return true; } /** * 设置发件人 * @access public * @param string $from 发件人地址 * @return boolean */ public function setFrom($from) { $this->_from = $from; return true; } /** * 设置收件人 * @access public * @param string $to 收件人地址 * @return boolean */ public function setReceiver($to) { $this->_to = $to; return true; } /** * 设置邮件信息 * @access public * @param string $body 邮件主题 * @param string $subject 邮件主体内容,可以是纯文本,也可是是HTML文本 * @return boolean */ public function setMailInfo($subject, $body) { $this->_subject = $subject; $this->_body = base64_encode($body); if(!empty($attachment)) { $this->_attachment = $attachment; } return true; } /** * 发送邮件 * @access public * @return boolean */ public function sendMail() { $command = $this->getCommand(); $this->socket(); foreach ($command as $value) { if($this->sendCommand($value[0], $value[1])) { continue; } else{ return false; } } //其实这里也没必要关闭,smtp命令:QUIT发出之后,服务器就关闭了连接,本地的socket资源会自动释放 $this->close(); echo 'Mail OK!'; return true; } /** * 返回错误信息 * @return string */ public function error(){ if(!isset($this->_errorMessage)) { $this->_errorMessage = ""; } return $this->_errorMessage; } /** * 返回mail命令 * @access protected * @return array */ protected function getCommand() { $separator = "----=_Part_" . md5($this->_from . time()) . uniqid(); //分隔符 $command = array( array("HELO sendmail\r\n", 250) ); if(!empty($this->_userName)){ $command[] = array("AUTH LOGIN\r\n", 334); $command[] = array($this->_userName . "\r\n", 334); $command[] = array($this->_password . "\r\n", 235); } //设置发件人 $command[] = array("MAIL FROM: <" . $this->_from . ">\r\n", 250); $header = "FROM: <" . $this->_from . ">\r\n"; //设置收件人 $command[] = array("RCPT TO: <" . $this->_to . ">\r\n", 250); $header .= "TO: <" . $this->_to . ">\r\n"; $header .= "Subject: " . $this->_subject ."\r\n"; $header .= "Content-Type: multipart/alternative;\r\n"; //邮件头分隔符 $header .= "\t" . 'boundary="' . $separator . '"'; $header .= "\r\nMIME-Version: 1.0\r\n"; $header .= "\r\n--" . $separator . "\r\n"; $header .= "Content-Type:text/html; charset=utf-8\r\n"; $header .= "Content-Transfer-Encoding: base64\r\n\r\n"; $header .= $this->_body . "\r\n"; $header .= "--" . $separator . "\r\n"; //结束数据 $header .= "\r\n.\r\n"; $command[] = array("DATA\r\n", 354); $command[] = array($header, 250); $command[] = array("QUIT\r\n", 221); return $command; } /** * 发送命令 * @access protected * @param string $command 发送到服务器的smtp命令 * @param int $code 期望服务器返回的响应吗 * @return boolean */ protected function sendCommand($command, $code) { echo 'Send command:' . $command . ',expected code:' . $code . '<br />'; //发送命令给服务器 try{ if(socket_write($this->_socket, $command, strlen($command))){ //当邮件内容分多次发送时,没有$code,服务器没有返回 if(empty($code)) { return true; } //读取服务器返回 $data = trim(socket_read($this->_socket, 1024)); echo 'response:' . $data . '<br /><br />'; if($data) { $pattern = "/^".$code."/"; if(preg_match($pattern, $data)) { return true; } else{ $this->_errorMessage = "Error:" . $data . "|**| command:"; return false; } } else{ $this->_errorMessage = "Error:" . socket_strerror(socket_last_error()); return false; } } else{ $this->_errorMessage = "Error:" . socket_strerror(socket_last_error()); return false; } }catch(Exception $e) { $this->_errorMessage = "Error:" . $e->getMessage(); } } /** * 建立到服务器的网络连接 * @access private * @return boolean */ private function socket() { if(!function_exists("socket_create")) { $this->_errorMessage = "Extension sockets must be enabled"; return false; } //创建socket资源 $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); if(!$this->_socket) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } socket_set_block($this->_socket);//设置阻塞模式 //连接服务器 if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } socket_read($this->_socket, 1024); return true; } /** * 关闭socket * @access private * @return boolean */ private function close() { if(isset($this->_socket) && is_object($this->_socket)) { $this->_socket->close(); return true; } $this->_errorMessage = "No resource can to be close"; return false; } } /**************************** Test ***********************************/ // $mail = new MySendMail(); // $mail->setServer("XXXX", "XXXXX@XXXXX", "XXXX"); // $mail->setFrom("XXXXX@XXXXX"); // $mail->setReceiver("XXXXX@XXXXX"); // $mail->setMailInfo("test", "<b>test</b>"); // $mail->sendMail(); ?>
2022年06月19日
112 阅读
0 评论
0 点赞
1
2
3