首页
关于
归档
朋友
壁纸
留言
API平台
告白墙
更多
休闲游戏
留言板
练字贴
Layui手册
Search
1
【PHP】PHPoffice/PHPSpreadsheet读取和写入Excel
1,339 阅读
2
【Git】No tracked branch configured for branch master or the branch doesn't exist.
1,038 阅读
3
【Layui】控制页面元素展示隐藏
858 阅读
4
【composer】composer常用命令
787 阅读
5
【PHP】PHP实现JWT生成和验证
769 阅读
默认分类
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
小破孩
累计撰写
223
篇文章
累计收到
33
条评论
首页
栏目
默认分类
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手册
搜索到
80
篇与
的结果
2025-03-13
【PHP】通联支付 通企付 生产签名 PHP版本
/** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2025/2/17 15:25 * @param $array * @return string * @Description:数组以key=value&key=value 返回字符串 */ public function arrayKeyValueToString($array) { $result = ''; foreach ($array as $key => $value) { $result.= $key. '='. $value. '&'; } // 去除末尾多余的 & 符号 return rtrim($result, '&'); } /** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2025/2/14 15:32 * @return string * @Description:生产签名 */ public function setSign() { $data = [ 'mchNo' => $this->payConfig['tppay_mchid'], // 商户号 'appId' => $this->payConfig['tppay_appid'], // appid 'reqTime' => $this->currentTimestamp, // 13位时间戳 'version' => "1.0", // 固定值 'signType' => 'RSA', // 验签方式 'mchOrderNo' => $this->orderNo, // 订单号 'amount' => (string)$this->amount, // 金额 单位 分 'body' => $this->body, // 商品描述 'notifyUrl' => $this->getNotifyUrl(), // 回调通知地址 'expiredTime' => '1800', // 订单超时支付时间 单位 秒 'channelExtra' => $this->channelExtra, 'payTypeInfo' => (string)$this->payTypeInfo(), // 收银台展示的付款方式 // 'directPayType'=> (string)$this->getPayType(), // 直接支付的支付方式 ]; ksort($data); // Log::write("发起签名的参数:".var_export($data,true),"tppay"); $instanceArr = new \app\common\lib\data\Arr(); $encodedParams = $instanceArr->arrayKeyValueToString($data); Log::write("处理后的签名字符串:".PHP_EOL.var_export($encodedParams,true),"tppay"); $privateKey = "-----BEGIN PRIVATE KEY-----\n" . $this->payConfig['tppay_rsa_private_key'] . "\n-----END PRIVATE KEY-----"; $publicKey = "-----BEGIN PUBLIC KEY-----\n" . $this->payConfig['tppay_rsa_public_key'] . "\n-----END PUBLIC KEY-----"; // Log::write("发起签名的私钥:".var_export($privateKey,true),"tppay"); $instanceRsa = new \app\common\lib\pay\tppay\Rsa(null, null, $privateKey, $publicKey); $encryptedWithPrivate = $instanceRsa->sign($encodedParams); //签名使用SHA1withRSA // Log::write("签名的结果:".var_export($encryptedWithPrivate,true),"tppay"); return $encryptedWithPrivate; }
2025年03月13日
6 阅读
0 评论
0 点赞
2025-03-13
【PHP】ThinkPHP6.1 参数验证中间件
public function handle($request, \Closure $next) { try { // 获取并清理参数 $params = array_filter(array_map(function ($value) { return is_string($value) ? trim($value) : $value; }, $request->param()), function ($value) { return is_numeric($value) || !empty($value); }); unset($params['controller'], $params['function']); if (empty($params)) return $next($request); // 设置请求属性,方便后续使用 $request->checkParam = $params; // 获取应用名、控制器和操作名 $appName = app('http')->getName(); $controller = Request::instance()->controller(true); $action = Request::instance()->action(true); // 动态构建验证器路径 $controllerParts = explode('.', $controller); $validatePathParts = array_merge([$appName, 'validate'], $controllerParts); $validatePath = implode('\\', array_map('ucfirst', $validatePathParts)); // 检查验证器是否存在及场景是否定义 if (!class_exists($validatePath) || !$this->sceneExists($validatePath, $action)) { return $next($request); } // 验证数据 $validateInstance = new $validatePath; if (!$validateInstance->scene($action)->check($params)) { throw new Exception($validateInstance->getError()); } } catch (Exception $e) { return show(100, $e->getMessage()); } return $next($request); } /** * 检查指定验证场景是否存在 * * @param string $validateClass 验证类名 * @param string $scene 场景名 * @return bool */ protected function sceneExists(string $validateClass, string $scene): bool { return (new $validateClass)->hasScene($scene); }
2025年03月13日
7 阅读
0 评论
0 点赞
2025-03-13
【PHP】发送腾讯云短信
优化空间很大,先用着,能用<?php namespace app\common\lib\sms\tencent; //缓存 use think\facade\Cache; use TencentCloud\Common\Credential; use TencentCloud\Common\Profile\ClientProfile; use TencentCloud\Common\Profile\HttpProfile; use TencentCloud\Common\Exception\TencentCloudSDKException; use TencentCloud\Sms\V20210111\SmsClient; use TencentCloud\Sms\V20210111\Models\SendSmsRequest; class Sms{ public $SecretID = "......................"; public $SecretKey = "......................."; public $SmsSdkAppId = "..........."; public $TemplateId = "........."; public $SignName = "............"; public $code; public $phone; public function __construct($phone = '', $code = '', $tempID = '') { $this->phone = $phone; $this->code = $code; if(!empty($tempID)){ $this->TemplateId = $tempID; } } public function send(){ try { //控制台 >API密钥管理页面获取 SecretID 和 SecretKey $cred = new Credential($this->SecretID, $this->SecretKey); //实例化一个http选项 [可选] $httpProfile = new HttpProfile(); $httpProfile->setEndpoint("sms.tencentcloudapi.com"); //实例化一个client选项 [可选] $clientProfile = new ClientProfile(); $clientProfile->setHttpProfile($httpProfile); /** * 实例化以sms为例的client对象, [第三个参数 可选] * * 第二个参数是地域信息,可以直接填 ap-guangzhou */ $client = new SmsClient($cred, "ap-beijing", $clientProfile); // 实例化一个sms发送短信请求对象,每个接口都会对应一个request对象。 $req = new SendSmsRequest(); //生成随机验证码 // $code = rand(11111, 99999); // $params = array( // //接收方手机号,带上+86 示例:+8613711112222 // "PhoneNumberSet" => array((string)$this->phone), // //短信应用ID:在 [短信控制台] 添加应用后生成的实际SdkAppId // "SmsSdkAppId" => (string)$this->SmsSdkAppId, // //短信签名内容:[不理解可以看文章里的截图] // "SignName" => (string)$this->SignName, // //模板ID:必须填写已审核通过的模板 // "TemplateId" => (string)$this->TemplateId, // //我的模板中有两个参数 第一个是验证码参数 第二个是有效时间 若无模板参数,则设置为空 // "TemplateParamSet" => array((string)$this->code, '10'), // //SecretID // // "SenderId" => (string)$this->SecretID // ); $params = array( "PhoneNumberSet" => array( (string)$this->phone ), "SmsSdkAppId" => (string)$this->SmsSdkAppId, "SignName" => (string)$this->SignName, "TemplateId" => (string)$this->TemplateId, "TemplateParamSet" => array( (string)$this->code), // "SenderId" => (string)$this->SecretID ); $req->fromJsonString(json_encode($params)); //发出请求,返回一个实例 $resp = $client->SendSms($req); // print_r($resp);die; //如果成功,把验证码存入缓存 //成功实例中的Code值为 Ok if ($resp->SendStatusSet[0]->Code === "Ok") { return true; // Cache::set('name', $code, 600); // return json(['msg' => "发送成功", 'code' => 200]); } } catch (TencentCloudSDKException $e) { echo $e; } } }
2025年03月13日
7 阅读
0 评论
0 点赞
2025-03-13
【PHP】打印猿&蜂打打 开放平台 完整对接
基础类<?php namespace app\common\lib\printman; use think\facade\Log; class Basic { #APPID public $AppId; #密钥 public $AppSecret; #API地址 public $ApiUrl; #打印机ID public $PrinterId; public function __construct($AppId, $AppSecret, $PrinterId) { $this->AppId = $AppId; $this->AppSecret = $AppSecret; $this->ApiUrl = "https://iot-app-prod.fengdada.cn/mk/api"; $this->PrinterId = $PrinterId; } public function encode($BizData, $nonce) { // global $AppSecret; $jsonBytes = mb_convert_encoding($BizData , 'utf-8'); $bizData = strval($jsonBytes); $sign_ori = $bizData . $nonce . $this->AppSecret; $md5_hash = md5($sign_ori, true); $sign = base64_encode($md5_hash); return $sign; } public function generate_verification_code() { $verification_code = ""; for ($i = 0; $i < 6; $i++) { $verification_code .= strval(rand(0, 9)); } return $verification_code; } public function requests_post($url, $data, $headers) { $ch = curl_init(); curl_setopt($ch, CURLOPT_CAINFO, "cacert-2023-01-10.pem"); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); return $response; } public function DoMyPost($URL, $json_BizData) { $ts = round(microtime(true) * 1000); $nonce = $this->generate_verification_code(); $sign = $this->encode($json_BizData, $nonce); $data = array( "bizData" => $json_BizData, "nonce" => $nonce, "appId" => $this->AppId, "timestamp" => strval($ts) ); $headers = array( 'Content-Type: application/json', 'sign:'.$sign ); // $response = $this->requests_post($URL, json_encode($data), $headers); $response = $this->curlRequest($URL, "POST",json_encode($data),true,false, $headers); Log::write("打印机日志:".print_r($response,true),'printman'); if(empty($response)) { echo "Error: no response received"; }else{ return $response; } } // 云打印验证码 public function PrintCaptcha() { $URL = $this->ApiUrl."/print/captcha"; $BizData = array('printerId' => $this->PrinterId); $json_BizData = json_encode($BizData); return $this->DoMyPost($URL, $json_BizData); } // 云打印机绑定 public function PrintBind($VerificationCode) { $URL = $this->ApiUrl."/printer/bind"; $BizData = array('printerId' => $this->PrinterId, 'captcha' => $VerificationCode); $json_BizData = json_encode($BizData); return $this->DoMyPost($URL, $json_BizData); } // 云打印 public function CloudPrint( $ShareCode, $PrintDataList) { $URL = $this->ApiUrl."/print"; $BizData = array('printerId' => $this->PrinterId, 'shareCode' => $ShareCode, 'printData' => $PrintDataList); $json_BizData = json_encode($BizData); return $this->DoMyPost($URL, $json_BizData); } // 云打印状态查询 public function QueryPrintStatus($ShareCode) { $URL = $this->ApiUrl."/printer/status/query"; $BizData = array('printerId' => $this->PrinterId, 'shareCode' => $ShareCode); $json_BizData = json_encode($BizData); return $this->DoMyPost($URL, $json_BizData); } //云打印解绑//0标识解绑失败,1标识解绑成功 public function unbind($ShareCode){ $URL = $this->ApiUrl."/printer/unbind"; $BizData = array('printerId' => $this->PrinterId, 'shareCode' => $ShareCode); $json_BizData = json_encode($BizData); return $this->DoMyPost($URL, $json_BizData); } /** * @Author: 小破孩嫩 * @Email: 3584685883@qq.com * @Time: 2021/4/1 10:39 * @param string $url url地址 * @param string $method 请求方法,默认为 'GET',可选值为 'GET' 或 'POST' * @param mixed $data 要发送的数据,如果是 POST 请求则为数据内容,否则为 null * @param array $headers 自定义请求头信息 * @param int $timeout 超时时间,默认为 30 秒 * @param bool $verifySSL 是否验证 SSL 证书,默认为 true * @param bool $flbg 返回值是否转成数组,默认不转 * @param bool $headercontent 是否获取请求的header值内容,默认不获取 * @return array|bool|mixed|string * @Description:curl请求 */ protected function curlRequest($url, $method = 'GET', $data = null, $flbg = false, $verifySSL = true, $headers = [], $headerContent = false, $timeout = 30) { // 初始化 cURL 会话 $ch = curl_init(); // 设置要请求的 URL curl_setopt($ch, CURLOPT_URL, $url); // 设置获取的信息以字符串形式返回,而不是直接输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 设置超时时间 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // 设置请求方法 if ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } // 设置请求头 if (!empty($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } // 设置是否验证 SSL 证书 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verifySSL); // 执行 cURL 会话并获取响应 $response = curl_exec($ch); // 获取 HTTP 响应码 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 如果 cURL 执行出错 if (curl_errno($ch)) { // 输出错误信息 echo 'Curl error: ' . curl_error($ch); // 关闭 cURL 会话并返回 false curl_close($ch); return false; } // 如果 HTTP 响应码大于等于 400(表示错误) elseif ($httpCode >= 400) { // 输出错误信息 echo "HTTP error: $httpCode"; // 关闭 cURL 会话并返回 false curl_close($ch); return false; } // 处理是否获取请求头内容 if ($headerContent && $httpCode == 200) { $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $headers = substr($response, 0, $headerSize); $body = substr($response, $headerSize); curl_close($ch); return [$headers, $body]; } // 关闭 cURL 会话 curl_close($ch); // 处理是否将响应转换为数组 if ($flbg) { $response = json_decode($response, true); } // 返回响应内容 return $response; } /** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2025/1/10 14:02 * @param $code * @return string * @Description:打印机错误码 */ public function errorCode($code){ $errorCodes = [ 200 => "success 成功", 500 => "sys fail 系统异常", 2001 => "sign check fail 签名失败", 2002 => "not find partner 查无合作伙伴", 2003 => "illegal access 非法访问", 3001 => "param check error 参数错误", 3002 => "please input params 请输入参数", 40001 => "please input APPID 请输入appid", 40002 => "biz exception 业务异常", 40003 => "printer xxx is offline 打印机离线", 40004 => "printer xxx is not auth 打印机未授权", 40005 => "shareCode is error 分享码错误", 40006 => "printer xxx after 5 minutes reprinting 请5分钟后重试", 40007 => "printer xxx captcha error 验证码错误", 40008 => "printer xxx captcha expired 验证码过期", 40009 => "printer xxx bind fail 绑定失败", 40023 => "lip not close 盖子未闭合", 40023 => "sticker 粘纸", 40023 => "sticker and lip not close 粘纸并且盖子未闭合", 40023 => "no page 缺纸", 40023 => "no page and lip not close 缺纸并且盖子未闭合", 40023 => "temperature too high 温度过高", 40023 => "temperature too high and lip not close 温度过高且盖子未闭合", 40023 => "temperature too high and sticker 温度过高且粘纸", 40023 => "temperature too high and lip not close and sticker 温度过高且粘纸,盖子未闭合", 40023 => "command error 指令错误" ]; return $errorCodes[$code]; } }模板<?php namespace app\common\lib\printman\template; use app\common\lib\printman\Template; class Temp1 implements Template { protected $id; public function __construct($id = "") { $this->id = $id; } /** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2025/1/10 10:51 * @return string * @Description:打印模板1 */ public function temp($order = ""){ if(empty($order)){ return "没有订单信息"; } $height = ceil(self::getTempHight($order)/10+50); $i = 40; $template = ""; $template .= "SIZE 72 mm, ".$height." mm\r\n"; $template .= "CODEPAGE 437\r\n"; $template .= "DENSITY 8\r\n"; $template .= "CLS \r\n"; $template .= "CODEPAGE 936\r\n"; $template .= "DIRECTION 0\r\n"; $template .= "TEXT 220,0,\"4\",0,1,1,\""."订单详情"."\"\r\n"; //小票标题 $template .= "TEXT 220,".$i.",\"4\",0,1,1,\"".""."\"\r\n"; //换行 $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"订单编号:".$order['o_uuid']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"打印时间:".date("Y-m-d H:i:s")."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"申 请 人:".$order['o_address_name']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"联系方式:".$order['o_address_tel_default']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"收货地址:".mb_substr($order['o_address_info'],0,16)."\"\r\n"; if(mb_strlen($order['o_address_info']) > 16){ $template .= "TEXT 40,"; $template .= $i+=30; $template .=",\"0\",0,1,1,\" ".mb_substr($order['o_address_info'],16)."\"\r\n"; } $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"申请时间:".$order['o_create_time']."\"\r\n"; // $template .= "TEXT 40,"; // $template .= $i+=30; // $template .= ",\"0\",0,1,1,\"审核时间:".date("Y-m-d H:i:s",$order['o_pay_receipt_allow_time'])."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"配 送 员:".$order['salesmaninfo']['sm_name']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"配送电话:".$order['salesmaninfo']['sm_phone']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"出货仓库:".$order['warehouse_name']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"商品总数:".$order['goods_total_num']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"商品总价:".$order['o_real_price']."\"\r\n"; $template .= "BAR 20,"; $template .= $i+=28; $template .= ",720,2\r\n"; $template .= "TEXT 40,"; $template .= $i+=16; $template .= ",\"0\",0,1,1,\"商品 数量 单价 金额\"\r\n"; $template .= "BAR 20,"; $template .= $i+=28; $template .= ",720,2\r\n"; foreach ($order['order_list'] as $kk => $vv){ if(!empty($vv['oi_issendgoods'])){ $firstNamaText = "赠品:"; }else{ $firstNamaText = "商品:"; } $knum = $kk+=1; $template .= "TEXT 30,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"$knum.". mb_substr($firstNamaText.$vv['oi_sku_info']['goods_info']['withgoodsinfoinfo']['sg_name'].'('.$vv['oi_sku_info']['sgcs_name'].')',0,26)."\"\r\n"; if(mb_strlen($firstNamaText.$vv['oi_sku_info']['goods_info']['withgoodsinfoinfo']['sg_name'].'('.$vv['oi_sku_info']['sgcs_name'].')') > 26){ $template .= "TEXT 30,"; $template .= $i+=30; $template .=",\"0\",0,1,1,\" ".mb_substr($firstNamaText.$vv['oi_sku_info']['goods_info']['withgoodsinfoinfo']['sg_name'].'('.$vv['oi_sku_info']['sgcs_name'].')',26)."\"\r\n"; } $template .= "TEXT 65,"; $template .= $i+=30; if(!empty($vv['oi_issendgoods'])){ $template .=",\"0\",0,1,1,\"".$vv['oi_sku_info']['num'].'件'.' '."0.00".' '."0.00"."\"\r\n"; }else{ $template .=",\"0\",0,1,1,\"".$vv['oi_sku_info']['num'].'件'.' '.sprintf("%.2f",$vv['oi_sku_info']['sgcs_price']/$vv['oi_sku_info']['num']).' '.$vv['oi_real_price']."\"\r\n"; } } $template .= "BAR 20,"; $template .= $i+=28; $template .= ",720,2\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"数量总计:".$order['goods_total_num'].'件'."\"\r\n"; $template .= "PRINT 1,1"; $instacneStr = new \app\common\lib\data\Str(); $data = [ 'waybillPrinterData' => $instacneStr->gzipAndBase64Encode($template), 'printType' => 'tspl', 'id' => $this->id ]; return [$data]; } protected function getTempHight($order){ $i = 50; $template = ""; $template .= "SIZE 72 mm, 90 mm\r\n"; $template .= "CODEPAGE 437\r\n"; $template .= "DENSITY 8\r\n"; $template .= "CLS \r\n"; $template .= "CODEPAGE 936\r\n"; $template .= "DIRECTION 0\r\n"; $template .= "TEXT 220,0,\"4\",0,1,1,\""."订单详情"."\"\r\n"; //小票标题 $template .= "TEXT 220,".$i.",\"4\",0,1,1,\"".""."\"\r\n"; //换行 $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"订单编号:".$order['o_uuid']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"打印时间:".date("Y-m-d H:i:s")."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"申 请 人:".$order['o_address_name']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"联系方式:".$order['o_address_tel_default']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"收货地址:".mb_substr($order['o_address_info'],0,16)."\"\r\n"; if(mb_strlen($order['o_address_info']) > 16){ $template .= "TEXT 40,"; $template .= $i+=30; $template .=",\"0\",0,1,1,\" ".mb_substr($order['o_address_info'],16)."\"\r\n"; } $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"申请时间:".$order['o_create_time']."\"\r\n"; // if(empty($order['o_help'])){ // $template .= "TEXT 40,"; // $template .= $i+=30; // $template .= ",\"0\",0,1,1,\"审核时间:".date("Y-m-d H:i:s",$order['o_pay_receipt_allow_time'])."\"\r\n"; // } $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"配送员姓名:".$order['salesmaninfo']['sm_name']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"配送员电话:".$order['salesmaninfo']['sm_phone']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"出货仓库:".$order['warehouse_name']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"商品总数:".$order['goods_total_num']."\"\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"商品总价:".$order['o_real_price']."\"\r\n"; $template .= "BAR 20,"; $template .= $i+=28; $template .= ",720,2\r\n"; $template .= "TEXT 40,"; $template .= $i+=16; $template .= ",\"0\",0,1,1,\"商品 数量 单价 金额\"\r\n"; $template .= "BAR 20,"; $template .= $i+=28; $template .= ",720,2\r\n"; // foreach ($order as $key => $val){ foreach ($order['order_list'] as $kk => $vv){ if(!empty($vv['oi_issendgoods'])){ $firstNamaText = "赠品:"; }else{ $firstNamaText = "商品:"; } $knum = $kk+=1; $template .= "TEXT 30,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"$knum.". mb_substr($firstNamaText.$vv['oi_sku_info']['goods_info']['withgoodsinfoinfo']['sg_name'].'('.$vv['oi_sku_info']['sgcs_name'].')',0,26)."\"\r\n"; if(mb_strlen($firstNamaText.$vv['oi_sku_info']['goods_info']['withgoodsinfoinfo']['sg_name'].'('.$vv['oi_sku_info']['sgcs_name'].')') > 26){ $template .= "TEXT 30,"; $template .= $i+=30; $template .=",\"0\",0,1,1,\" ".mb_substr($firstNamaText.$vv['oi_sku_info']['goods_info']['withgoodsinfoinfo']['sg_name'].'('.$vv['oi_sku_info']['sgcs_name'].')',26)."\"\r\n"; } $template .= "TEXT 65,"; $template .= $i+=30; $template .=",\"0\",0,1,1,\"".$vv['oi_sku_info']['num'].'件'.' '.$vv['oi_sku_info']['sgcs_price'].' '.$vv['oi_sku_info']['sgcs_price']*$vv['oi_sku_info']['num']."\"\r\n"; } $template .= "BAR 20,"; $template .= $i+=28; $template .= ",720,2\r\n"; $template .= "TEXT 40,"; $template .= $i+=30; $template .= ",\"0\",0,1,1,\"数量总计:".$order['goods_total_num']."\"\r\n"; // } $template .= "PRINT 1,1"; return $i; } }
2025年03月13日
5 阅读
0 评论
0 点赞
2025-03-13
【PHP】给富文本内容的图片,视频,文件 拼接当前网址域名
/** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2024/11/18 15:20 * @param $text * @param $domain * @return string|string[]|null * @Description:给服务文本拼接当前网址域名 */ public function addDomainToPaths($text, $domain){ // 匹配图片路径 $text = preg_replace('/<img.*?src="([^"]+)"/i', '<img src="' . $domain . '$1"', $text); // 匹配视频路径 $text = preg_replace('/<video.*?src="([^"]+)"/i', '<video src="' . $domain . '$1"', $text); // 匹配文件路径(可根据具体文件类型的链接特征进行修改) $text = preg_replace('/<a.*?href="([^"]+)"/i', '<a href="' . $domain . '$1"', $text); return $text; }
2025年03月13日
9 阅读
0 评论
0 点赞
2025-03-13
【PHP】过滤富文本内容
/** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2024/10/24 13:50 * @param $text * @return string|string[]|null * @Description:过滤富文本 */ public static function filterRichText($text){ // 定义要过滤的 SQL 关键字模式 $sqlPatterns = [ '/\b(SELECT|INSERT|UPDATE|DELETE|FROM|WHERE|AND|OR|JOIN|DROP|CREATE|ALTER|TRUNCATE|GRANT|REVOKE|SET)\b/i', '/\b(AS|LIKE|NOT|IN|BETWEEN|IS|NULL|COUNT|SUM|AVG|MIN|MAX)\b/i', '/\b(UNION|ALL|ANY|EXISTS)\b/i', '/\b(ORDER\s+BY|LIMIT)\b/i' ]; // 定义要过滤的常见函数模式 $functionPatterns = [ '/\b(function\s+\w+\s*\([^)]*\))\b/i', '/\b(eval|exec|system|passthru|shell_exec|assert)\b/i' ]; // 定义要过滤的特殊字符和表达式模式 $specialPatterns = [ '/\$\{.*?\}/', // 过滤类似 ${expression} 的表达式 '/@.*?;/', // 过滤以 @ 开头并以 ; 结尾的表达式 '/\b(phpinfo|var_dump)\b/i', // 过滤特定的 PHP 函数 '/<\s*(script|iframe|object|embed|applet)[^>]*>/i' // 过滤危险的脚本标签 ]; // 定义要过滤的危险属性模式 $dangerousAttributesPatterns = [ '/on\w+\s*=/i', // 过滤以 "on" 开头的事件属性 '/javascript:[^"]*"/i' // 过滤 JavaScript 协议的链接 ]; // 先过滤 SQL 关键字 $filteredText = preg_replace($sqlPatterns, '', $text); // 再过滤函数 $filteredText = preg_replace($functionPatterns, '', $filteredText); // 然后过滤特殊字符和表达式 $filteredText = preg_replace($specialPatterns, '', $filteredText); // 接着过滤危险的属性 $filteredText = preg_replace($dangerousAttributesPatterns, '', $filteredText); // 处理可能出现的连续空格 $filteredText = preg_replace('/\s+/', ' ', $filteredText); // 去除前后的空格 $filteredText = trim($filteredText); // 转换 HTML 实体 $filteredText = htmlentities($filteredText, ENT_QUOTES, 'UTF-8'); return $filteredText; }
2025年03月13日
7 阅读
0 评论
0 点赞
2025-03-13
【PHP】获取二维数组里面最小的值
/** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2024/12/5 17:16 * @param $array * @return array * @Description:获取一个二维数组,数据最小的,并返回对应的key和value */ public function getMinValueKey($array) { $minValue = PHP_INT_MAX; $desiredKey = null; foreach ($array as $key => $subArray) { foreach ($subArray as $subKey => $value) { if ($value < $minValue) { $minValue = $value; $desiredKey = $subKey; } } } return [$desiredKey, $minValue]; } //使用场景 $inatanceMap = new \app\common\lib\map\baidu\Lnglat($this->param['ac_address']); $lnglat = $inatanceMap->addressToLngLat(); $this->param['u_lng'] = $lnglat['lng'];//经度 $this->param['u_lat'] = $lnglat['lat'];//纬度 $companyList = M("AdminCompany")::getCompanyListUseSelect(); $instanceDis = new \app\common\lib\map\Distance(); foreach ($companyList as $key => $val){ $arrAddress[$key][$val['ac_uuid']] = $instanceDis->getdistance($val['ac_lng'],$val['ac_lat'],$lnglat['lng'],$lnglat['lat']); } $instanceArr = new \app\common\lib\data\Arr(); list($minKey, $minValue) = $instanceArr->getMinValueKey($arrAddress); $this->param['u_company_uuid'] = $minKey; $this->param['u_address'] = $this->param['ac_address'];
2025年03月13日
7 阅读
0 评论
0 点赞
2025-03-13
【PHP】按照个商品金额,等比例分配优惠劵
/** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2024/11/23 11:41 * @param $products ['id' => 'price','id' => price] * @param $totalCouponAmount 优惠劵优惠金额 * @return array * @Description:按照商品比例拆分优惠劵,分配给对应的商品 */ public function getSplitCoupon($products, $totalCouponAmount) { $totalAmount = array_sum($products); $discounts = []; $allocatedDiscount = 0; foreach ($products as $id => $amount) { $ratio = $amount / $totalAmount; $discount = $ratio * $totalCouponAmount; $roundedDiscount = round($discount, 2); $discounts[$id] = $roundedDiscount; $allocatedDiscount += $roundedDiscount; } // 调整以使总和为指定的优惠券总额 $diff = $totalCouponAmount - $allocatedDiscount; if ($diff!= 0) { $sortedDiscounts = $discounts; arsort($sortedDiscounts); $i = 0; foreach ($sortedDiscounts as $id => $discount) { if ($i < abs($diff)) { $discounts[$id] += ($diff > 0)? 0.01 : -0.01; } $i++; } } return $discounts; }
2025年03月13日
5 阅读
0 评论
0 点赞
2023-07-20
【PHP】打开文件路径的所有文件
<?php function open_dir($path) { if (!is_dir($path) || empty($path)) die("该" . $path . "不是目录"); $path = $path . '/'; $fileList = []; $dirFile = scandir($path); if (!empty($dirFile) && is_array($dirFile)) { foreach ($dirFile as $file) { if ($file != '.' && $file != '..') { $fullPath = $path . $file; if (is_dir($fullPath)) { // 子文件夹,进行递归 $fileList[$file] = open_dir($fullPath); } else { //根目录下的文件 $fileList[] = $file; } } } } return $fileList; } $list = open_dir("/www/wwwroot/8688web.com/one"); // echo '<pre>'; // print_r($list); // echo '</pre>'; ?>
2023年07月20日
179 阅读
0 评论
0 点赞
2023-07-13
【PHP】$_SERVER内容
Array ( [ALLUSERSPROFILE] => C:\ProgramData [APPDATA] => C:\Users\Administrator\AppData\Roaming [CommonProgramFiles] => C:\Program Files\Common Files [CommonProgramFiles(x86)] => C:\Program Files (x86)\Common Files [CommonProgramW6432] => C:\Program Files\Common Files [COMPUTERNAME] => USER-20230417GP [ComSpec] => C:\Windows\system32\cmd.exe [DriverData] => C:\Windows\System32\Drivers\DriverData [EFC_7072] => 1 [FPS_BROWSER_APP_PROFILE_STRING] => Internet Explorer [FPS_BROWSER_USER_PROFILE_STRING] => Default [HOMEDRIVE] => C: [HOMEPATH] => \Users\Administrator [LOCALAPPDATA] => C:\Users\Administrator\AppData\Local [LOGONSERVER] => \\USER-20230417GP [NUMBER_OF_PROCESSORS] => 4 [OneDrive] => C:\Users\Administrator\OneDrive [OS] => Windows_NT [Path] => C:\Program Files (x86)\Common Files\NetSarang;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;E:\krhwork\phpstudy_pro\Extensions\php\php7.3.4nts;C:\ProgramData\ComposerSetup\bin;D:\krhsoftware\Git\cmd;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;C:\Users\Administrator\AppData\Roaming\Composer\vendor\bin [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC [PROCESSOR_ARCHITECTURE] => AMD64 [PROCESSOR_IDENTIFIER] => Intel64 Family 6 Model 158 Stepping 10, GenuineIntel [PROCESSOR_LEVEL] => 6 [PROCESSOR_REVISION] => 9e0a [ProgramData] => C:\ProgramData [ProgramFiles] => C:\Program Files [ProgramFiles(x86)] => C:\Program Files (x86) [ProgramW6432] => C:\Program Files [PSModulePath] => C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules [PUBLIC] => C:\Users\Public [SESSIONNAME] => Console [SystemDrive] => C: [SystemRoot] => C:\Windows [TEMP] => C:\Users\ADMINI~1\AppData\Local\Temp [TMP] => C:\Users\ADMINI~1\AppData\Local\Temp [USERDOMAIN] => USER-20230417GP [USERDOMAIN_ROAMINGPROFILE] => USER-20230417GP [USERNAME] => Administrator [USERPROFILE] => C:\Users\Administrator [windir] => C:\Windows [HTTP_COOKIE] => thinkphp_show_page_trace=0|0; thinkphp_show_page_trace=0|0; PHPSESSID=42ebce2914dea21a3b2a6408724e3b03; thinkphp_show_page_trace=0|0; web_token=74a57df797654a2f56951be092c992e1; user_uuid=20221111111111000001 [HTTP_ACCEPT_LANGUAGE] => zh-CN,zh;q=0.9 [HTTP_ACCEPT_ENCODING] => gzip, deflate [HTTP_REFERER] => http://local.huizhan.com/backend/business.register/index [HTTP_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.7 [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 [HTTP_UPGRADE_INSECURE_REQUESTS] => 1 [HTTP_CACHE_CONTROL] => max-age=0 [HTTP_CONNECTION] => keep-alive [HTTP_HOST] => local.huizhan.com [REDIRECT_STATUS] => 200 [SERVER_NAME] => local.huizhan.com [SERVER_PORT] => 80 [SERVER_ADDR] => 127.0.0.1 [REMOTE_PORT] => 61008 [REMOTE_ADDR] => 127.0.0.1 [SERVER_SOFTWARE] => nginx/1.15.11 [GATEWAY_INTERFACE] => CGI/1.1 [REQUEST_SCHEME] => http [SERVER_PROTOCOL] => HTTP/1.1 [DOCUMENT_ROOT] => E:/krhwork/phpstudy_pro/WWW/thinkphp/huizhan/public [DOCUMENT_URI] => /index.php [REQUEST_URI] => /backend/business.register/index [SCRIPT_NAME] => /index.php [CONTENT_LENGTH] => [CONTENT_TYPE] => [REQUEST_METHOD] => GET [QUERY_STRING] => s=//backend/business.register/index [PATH_TRANSLATED] => E:/krhwork/phpstudy_pro/WWW/thinkphp/huizhan/public [PATH_INFO] => [SCRIPT_FILENAME] => E:/krhwork/phpstudy_pro/WWW/thinkphp/huizhan/public/index.php [FCGI_ROLE] => RESPONDER [PHP_SELF] => /index.php [REQUEST_TIME_FLOAT] => 1689236577.974 [REQUEST_TIME] => 1689236577 )
2023年07月13日
154 阅读
0 评论
0 点赞
2023-06-09
【PHP】PHP实现二维数组转一维数组
可以使用 array_reduce() 函数将二维数组转换为一维数组。array_reduce() 函数将通过一个回调函数迭代数组中的所有值,并将它们合并为一个单一的值。在这种情况下,我们将使用 array_merge() 函数将所有子数组合并为一个单一的数组。示例代码如下:function flatten_array($arr) { return array_reduce($arr, function($carry, $item) { return array_merge($carry, is_array($item) ? flatten_array($item) : array($item)); }, array()); } // 测试 $arr = array( array(1, 2, 3), array(4, 5, 6), array( array(7, 8), 9, array(10, 11, 12), ), ); $result = flatten_array($arr); print_r($result); // 输出: // Array // ( // [0] => 1 // [1] => 2 // [2] => 3 // [3] => 4 // [4] => 5 // [5] => 6 // [6] => 7 // [7] => 8 // [8] => 9 // [9] => 10 // [10] => 11 // [11] => 12 // )在上面的示例代码中,我们定义了一个 flatten_array() 函数,该函数使用 array_reduce() 函数和递归调用来将二维数组转换为一维数组。
2023年06月09日
299 阅读
0 评论
0 点赞
2023-05-08
【PHP】PHP实现金额检测
public function checkMoney($value) { if (!is_numeric($value)) { return false; } if ($value <= 0) { return false; } if (preg_match('/^[0-9]+(\.\d{1,2})?$/',$value)) { return true; } else { return false; } } 优化 public function checkMoney($value) { if(is_array($value)){ foreach ($value as $v){ $this->checkMoney($v); } }else{ if (!is_numeric($value)) { return $this->show('100','金额不正确'); } if ($value <= 0) { return $this->show('100','金额不正确'); } if (preg_match('/^[0-9]+(\.\d{1,2})?$/',$value)) { return true; } else { return $this->show('100','金额不正确'); } } }
2023年05月08日
181 阅读
0 评论
0 点赞
2023-04-27
【PHP】针对时间段的处理
/** * 获取最近七天所有日期 */ public function getWeeks($time = '', $format='Y-m-d'){ $time = $time != '' ? $time : time(); //组合数据 $date = []; for ($i=1; $i<=7; $i++){ $date[$i] = date($format ,strtotime( '+' . $i-7 .' days', $time)); } return $date; } /** * 获取起始日期中的所有日期 * @param $start 开始时间 2022-09-22 * @param $end 结束时间 2022-09-29 * @return array */ public function getBetweenTime($start, $end){ $response = []; $dt_start = strtotime($start); $dt_end = strtotime($end); while ($dt_start <= $dt_end) { array_push($response, date('Y-m-d', $dt_start)); $dt_start = strtotime('+1 day', $dt_start); } return $response; } /** * 获取起始时间戳 * @param string $type 类型 1本年 2本季度 3上月 4本月 5本周 6上周 7下周 * @return string */ public function getStartEndtime($type=''){ switch ($type) { case 1: //本年开始 $startTime = strtotime(date("Y", time()) . "-1" . "-1"); //本年结束 $overTime = strtotime(date("Y", time()) . "-12" . "-31"); break; case 2: //获取当前季度 $season = ceil((date('m')) / 3); $startTime = mktime(00, 00, 00, $season * 2 + 1, 1, date('Y')); $overTime = mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')); break; case 3: //上月 $startTime = mktime(0,0,0,date("m")-1,1,date("Y")); $overTime = mktime(0,0,0,date("m"),1,date("Y"))-1; break; case 4: //本月 $startTime = mktime(0, 0, 0, date('m'), 1, date('Y')); $overTime = mktime(23, 59, 59, date('m'), date('t'), date('Y')); break; case 5: //本周 $startTime=mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y')); $overTime=mktime(23,59,59,date('m'),date('d')-date('w')+7,date('Y')); break; case 6: //上周 $startTime=mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y')); $overTime=mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y')); break; case 7: //下周 $startTime=mktime(0,0,0,date('m'),date('d')-date('w')+1+7,date('Y')); $overTime=mktime(23,59,59,date('m'),date('d')-date('w')+7+7,date('Y')); break; default: //今天 $startTime = mktime(0,0,0,date("m"),date("d"),date("Y")); $overTime = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1; break; } return ['statTime'=>$startTime,'endTime'=>$overTime]; } /** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2024/11/11 11:34 * @return array * @Description:获取当前时间到一周前的时间 */ public function getTimeStamps() { $todayEnd = strtotime(date('Y-m-d 23:59:59')); $sevenDaysAgoStart = strtotime('-6 days 00:00:00'); return [ 'start' => $sevenDaysAgoStart, 'end' => $todayEnd ]; } /** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2024/12/7 11:05 * @param $year * @param $month * @return array * @Description:获取指定月份的开始时间和结束时间 */ public function getMonthStartAndEndTime($year, $month) { $startTime = strtotime($year. '-'. $month. '-01 00:00:00'); $endTime = strtotime($year. '-'. $month. '-'. date('t', strtotime($year. '-'. $month. '-01')). ' 23:59:59'); return ['statTime'=>$startTime,'endTime'=>$endTime]; }
2023年04月27日
261 阅读
0 评论
0 点赞
2023-03-23
【PHP】php.ini如何配置,才是PHP性能最大优化?
内存 默认设置memory_limit = 128M单个进程可使用的内存最大值,这个值的设定可以从以下几点考虑:应用的类型。如果是内存集中型应用,可增加该值;单个 PHP 进程平均消耗的内存,该值可通过多次运行同一个脚本来计算平均值;能负担多少个 php-fpm 进程;该值等于分配的总内存除以单个 PHP 进程平均消耗的内存文件上传 默认设置file_uploads = On max_file_uploads = 20 upload_max_filesize = 2M max_execution_time = 30 值 为 0 代表没有限制设置max_file_uploads来决定同时允许多少个文件上传;设置upload_max_filesize来决定每个文件上传的最大值;如果是长时间任务,尽量使用队列来处理,因此,可适当缩短max_execution_time的值;注意, Web 服务器也可以设置文件上传大小及超时时间,不能仅仅以 php.ini 的设置为准;会话 PHP 的会话默认是保存在硬盘中session.save_handler = files在实际应用中,应当将会话保存在内存中。可使用 Memcached 或者 Redis。这样做主要有两个好处:提高速度;有助于后期的扩展,如果会话数据存储在硬盘中,不便于增加额外的服务器,如果把会话数据存放在 Memcached 或 Redis 里,任何一台分布式 PHP-FPM 服务器都能访问会话数据。可通过 PECL 安装memcached扩展并设置默认的save_handler为memcachedsession.save_handler = 'memcached' session.save_path = '127.0.0.1:11211'缓冲输出 默认值realpath_cache_size = 4M realpath_cache_ttl = 120PHP 会缓存应用使用的文件路径,这样每次包含或导入文件时就无需不断搜索包含路径了,这个缓存叫真实路径缓存(realpath cache),如果运行的是大型的 PHP 文件(如 Composer 组件),使用了大量文件,增加 PHP 真实路径缓存的大小能得到更好的性能。
2023年03月23日
279 阅读
0 评论
0 点赞
2022-09-14
【PHP】PHP实现协同推荐算法
概述: 因为最近对算法这块进行了学习,所以最近对类似淘宝商品推荐的协同推荐算法进行了整理总结,本文将用php语言进行实现,文章将从以下几点进行终结: (1)什么是协同推荐算法?有什么用? (2)依据什么数学方法公式,为什么要用它? (3)实现流程是怎样的? (4)具体实现步骤。 首先,第一点,我们要实现一个算法必须要知道它有什么用,核心思想是什么?顾名思义,它的用途就是用来给我们做一些相似性推荐,推荐你喜欢的恭喜,根据你的好友等预测你喜欢的然后再推荐给你;我们举个例子来概括一下算法的核心思想:该算法的核心思想可以概括为:若a,b喜欢同一系列的物品(暂时称b是a的邻居吧),则a很可能喜欢b喜欢的其他物品。算法的实现流程可以简单概括为:1.确定a有哪些邻居 2.通过邻居来预测a可能会喜欢哪种物品 3.将a可能喜欢的物品推荐给a。 现在我们了解了这个核心思想以后,我们知道算法的核心是数学逻辑,我们必须理解其数学思想,然后再转化为编程思想达到我们的目标: 我们先回忆一下余弦定理: 可见cosA的夹角越小cosA的值越大,则边c和边b的长度越相近,因此我们利用余弦定理的向量方式类推出如下公式:1.余弦相似度(求邻居):2.预测公式(预测a可能会喜欢哪种物品): 接下来我们介绍一下实现流程: 现在我们具体看看怎样用php实现这个算法: (1)数据准备:在这里我们直接定义一组数据$userarray= [ ['name'=>'A','a'=>3,'b'=>2,'c'=>1,'d'=>5,'e'=>null,'f'=>null,'g'=>null], ['name'=>'B','a'=>1,'b'=>6,'c'=>6,'d'=>5,'e'=>2,'f'=>3,'g'=>5], ['name'=>'C','a'=>3,'b'=>5,'c'=>null,'d'=>4,'e'=>3,'f'=>3,'g'=>6], ['name'=>'D','a'=>4,'b'=>1,'c'=>1,'d'=>5,'e'=>3,'f'=>3,'g'=>3], ['name'=>'E','a'=>5,'b'=>1,'c'=>null,'d'=>4,'e'=>5,'f'=>1,'g'=>5], ['name'=>'F','a'=>1,'b'=>3,'c'=>2,'d'=>5,'e'=>6,'f'=>null,'g'=>4], ['name'=>'G','a'=>1,'b'=>5,'c'=>2,'d'=>5,'e'=>2,'f'=>3ll,'g'=>5] ]; (2)我们以A用户为对象分别计算出他们的余弦相似度,然后将其存入数组$cos中:/* * 以下示例只求A的推荐 */ $cos = []; $cos[0] = 0; $denominator_left = 0;//分母左边初始值 //开始计算cos //计算分母左边 for($i=1;$i<8;$i++){ if($userarray[0][$i] != null){//$userarray[0]代表A $denominator_left += $userarray[0][$i] * $userarray[0][$i]; } } $denominator_left = sqrt($denominator_left);//取算数平方根的值 for($i=1;$i<6;$i++){ $numerator = 0;//分子初始值 $denominator_right = 0;//分母右边初始值 for($j=1;$j<8;$j++){ //计算分子 if($userarray[0][$j] != null && $userarray[$i][$j] != null){ $numerator += $userarray[0][$j] * $userarray[$i][$j]; } //计算分母右边 if($userarray[$i][$j] != null){ $denominator_right += $userarray[$i][$j] * $userarray[$i][$j]; } } $denominator_right = sqrt($denominator_right ); $cos[$i]['cos'] = $numerator /$denominator_left /$denominator_right ;//存储当前用户的cos近似值 $cos[$i]['name'] = $userarray[$i]['name'];//存储当前用户的名字 $cos[$i]['e'] = $userarray[$i]['e'];//存储当前用户的e物品评分 $cos[$i]['f'] = $userarray[$i]['f'];//存储当前用户的f物品评分 $cos[$i]['g'] = $userarray[$i]['g'];//存储当前用户的g物品评分 }(3)我们对余弦近似值进行由大到小的排序,抽取前三个用户作为A用户的邻居,我们使用冒泡排序法对其进行排序// 第一层可以理解为从数组中键为0开始循环到最后一个 for ($i = 0; $i < count($cos) ; $i++) { // 第二层为从$i+1的地方循环到数组最后 for ($j = $i+1; $j < count($cos); $j++) { // 比较数组中两个相邻值的大小 if ($cos[$i]['cos'] < $cos[$j]['cos']) { $tem = $cos[$i]; // 这里临时变量,存贮$i的值 $cos[$i] = $cos[$j]; // 第一次更换位置 $cos[$j] = $tem; // 完成位置互换 } } } (4)接下来我们对A用户可能喜欢的物品进行预测,利用第二个公式,求出product值//计算A对e的评分 $numerator= 0;//分子初始值 $denominator= 0;//分母初始值 for($i=0;$i<3;$i++){ $numerator+= $cos[$i]['cos'] * $cos[$i]['e']; $denominator+= $cos[$i]['cos']; } $score_e = $numerator/sqrt($denominator); //计算A对f的评分 $numerator= 0;//分子初始值 $denominator= 0;//分母初始值 for($i=0;$i<3;$i++){ $numerator+= $cos[$i]['cos'] * $cos[$i]['f']; $denominator+= $cos[$i]['cos']; } $score_f= $numerator/sqrt($denominator); //计算A对g的评分 $numerator= 0;//分子初始值 $denominator= 0;//分母初始值 for($i=0;$i<3;$i++){ $numerator+= $cos[$i]['cos'] * $cos[$i]['g']; $denominator+= $cos[$i]['cos']; } $score_g= $numerator/sqrt($denominator);最后我们可以比较这些值,可以选取值最大的物品推荐给用户A
2022年09月14日
347 阅读
0 评论
1 点赞
2022-09-01
【PHP】PHP错误级别
在php编程过程中,大家一定会遇到或多或少的错误提醒,也正是这些错误提示,指引我们编写更加干净的代码,今天先写出我们主要列出的错误类型,先挖坑,写关于php错误与异常的相关知识,慢慢填坑。Deprecated最低级别错误,程序继续执行Notice 通知级别的错误 如直接使用未声明变量,程序继续执行 Warning 警告级别的错误,可能得不到想要的结果 Fatal error 致命级别错误致命级别错误,程序不往下执行 parse error 语法解析错误,最高级别错误,连其他错误信息也不呈现出来 E_USER_相关错误 用户设置的相关错误利用trigger_error()函数设置一个用户级别的 error/warning/notice 信息如何设置错误级别? error_reporting(-1)显示所有错误,error_reporting(0)屏蔽所有错误。ini_set('error_reporting',0)也是屏蔽所有错误。可以在php.ini文件中设置error_reporting来使脚本显示或不显示某些错误。ini_set('display_errors','On')显示错误。 注意:error_reporting()设置报告何种错误,而ini_set('display_errors','On')设置是否在输出错误。因而error_reporting(-1)和ini_set('display_errors',0)可用作设置日志:报告错误并且不输出。 举例:error_reporting(E_ALL&~E_NOTICE)不显示通知级别的错误。“~”表示非。
2022年09月01日
214 阅读
0 评论
0 点赞
2022-08-16
【PHP】PHPEmail的使用
第一步:使用composer安装phpmailercomposer require phpmailer/phpmailer第二步:common.php写个发送邮件的函数(腾讯邮箱的为例)/** * 系统邮件发送函数 * @param string $tomail 接收邮件者邮箱 * @param string $name 接收邮件者名称 * @param string $subject 邮件主题 * @param string $body 邮件内容 * @param string $attachment 附件列表 * @return boolean * @author static7 <static7@qq.com> */ function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) { $mail = new \PHPMailer(); //实例化PHPMailer对象 $mail->CharSet = 'UTF-8'; //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码 $mail->IsSMTP(); // 设定使用SMTP服务 $mail->SMTPDebug = 0; // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息 $mail->SMTPAuth = true; // 启用 SMTP 验证功能 $mail->SMTPSecure = 'ssl'; // 使用安全协议 $mail->Host = "smtp.exmail.qq.com"; // SMTP 服务器 $mail->Port = 465; // SMTP服务器的端口号 $mail->Username = "static7@qq.com"; // SMTP服务器用户名 $mail->Password = ""; // SMTP服务器密码 $mail->SetFrom('static7@qq.com', 'static7'); $replyEmail = ''; //留空则为发件人EMAIL $replyName = ''; //回复名称(留空则为发件人名称) $mail->AddReplyTo($replyEmail, $replyName); $mail->Subject = $subject; $mail->MsgHTML($body); $mail->AddAddress($tomail, $name); if (is_array($attachment)) { // 添加附件 foreach ($attachment as $file) { is_file($file) && $mail->AddAttachment($file); } } return $mail->Send() ? true : $mail->ErrorInfo; }第三步:控制器方法里写发送的内容/** * tp5邮件 * @param * @author staitc7 <static7@qq.com> * @return mixed */ public function email() { $toemail='static7@qq.com'; $name='static7'; $subject='QQ邮件发送测试'; $content='恭喜你,邮件测试成功。'; dump(send_mail($toemail,$name,$subject,$content)); }第4步:测试发送请自行测试转发:https://www.thinkphp.cn/topic/44477.html
2022年08月16日
244 阅读
0 评论
0 点赞
2022-06-29
【PHP】PHP报错ssl3_get_server_certificate:certificate verify failed问题
getimagesize(): SSL operation failed with code 1. OpenSSL Error message:error14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed提示缺少证书,搜到很多帖子写的感觉不是很清楚,以下步骤我自己记录一下先下载cacert.pem证书, https://curl.se/ca/cacert.pem,下载完后我直接上传到了/www/server/php目录下找到对应的php版本的php.ini文件将openssl.cafile其路径替换为openssl.cafile=/www/server/php/cacert.pem也就是你刚把cacert.pem证书上传的路径最后重启php服务即可
2022年06月29日
215 阅读
0 评论
0 点赞
2022-06-28
【PHP】PHP获取开始时间结束时间方法总汇
<?php /** * @author yfl QQ554665488 * demo Time funtion */ //返回今天的开始时间和结束时间 function day_now() { $arr = [ mktime(0, 0, 0, date('m'), date('d'), date('Y')), mktime(23, 59, 59, date('m'), date('d'), date('Y')), ]; return $arr; } //返回昨天开始结束时间 改造上边的方法 function day_yesterday() { $yesterday = date('d') - 1; $arr = [ mktime(0, 0, 0, date('m'), $yesterday, date('Y')), mktime(23, 59, 59, date('m'), $yesterday, date('Y')), ]; return $arr; } //获取当前时间的本周开始结束时间 function week_now() { $arr = [ strtotime(date('Y-m-d', strtotime("-1 week Monday", time()))), strtotime(date('Y-m-d', strtotime("+0 week Sunday", time()))) - 1 ]; return $arr; } // var_dump(week_now()); // echo date('Y-m-d',strtotime('next Monday',time())); //返回上周开始和结束的时间戳 function last_week() { // 1520179200 1520783999 $arr = [ // date('Y-m-d',strtotime('last week Monday',time())), // date('Y-m-d',strtotime('last week Sunday',time())) strtotime('last week Monday', time()), strtotime('last week Sunday +1 days -1 seconds', time()) ]; return $arr; } // var_dump(last_week()); // 返回本月开始和结束的时间戳 function now_month() { $arr = [ mktime(0, 0, 0, date('m'), 1, date('Y')), mktime(23, 59, 59, date('m'), date('t'), date('Y')) ]; return $arr; } // var_dump(now_month()); // 返回某一年某一月的开始和结束的时间戳 function month_year($year, $month) { return [ $begin = mktime(0, 0, 0, $month, 1, $year), $end = mktime(23, 59, 59, $month, date('t', $begin), $year) ]; } // var_dump(month_year(2017,3)); // 返回当前季度的开始时间和结束时间 function now_quarter($month = 0) { $month = $month != 0 ? $month : date('n'); $season = ceil($month / 3); return [ mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')), mktime(0, 0, 0, $season * 3, date('t'), date('Y')) - 1 ]; } // var_dump(now_quarter()); // 返回上个月开始和结束的时间戳 function lastMonth() { $begin = mktime(0, 0, 0, date('m') - 1, 1, date('Y')); $end = mktime(23, 59, 59, date('m') - 1, date('t', $begin), date('Y')); return [$begin, $end]; } // var_dump(lastMonth());
2022年06月28日
220 阅读
0 评论
0 点赞
2022-06-27
【PHP】TP6.0验证码接口
安装验证码扩展:composer require topthink/think-captcha创建验证码接口: public function setYzm(){ $captcha_img = Captcha_src(); $src = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/api'.captcha_src(); ob_clean(); //清除缓冲区,防止出现“图像因其本身有错无法显示'的问题 $type = getimagesize($src)['mime']; //获取图片类型 header("Content-Type:{$type}"); $imgData = file_get_contents($src); //获取图片二进制流 $base64String = 'data:' . $type . ';base64,' . base64_encode($imgData); return show(200,'请求成功',$base64String); } 可以不用base64处理直接返回验证码地址 public function checkYzm($yzm){ if(!Captcha::checkApi($yzm)) throw new Exception('验证码验证失败~'); return true; }修改底层配置路径:vendor/topthink/think-captcha/src/Captcha.php/** * 创建验证码 * @return array * @throws Exception */ protected function generate(): array { $bag = ''; if ($this->math) { $this->useZh = false; $this->length = 5; $x = random_int(10, 30); $y = random_int(1, 9); $bag = "{$x} + {$y} = "; $key = $x + $y; $key .= ''; } else { if ($this->useZh) { $characters = preg_split('/(?<!^)(?!$)/u', $this->zhSet); } else { $characters = str_split($this->codeSet); } for ($i = 0; $i < $this->length; $i++) { $bag .= $characters[rand(0, count($characters) - 1)]; } $key = mb_strtolower($bag, 'UTF-8'); } $hash = password_hash($key, PASSWORD_BCRYPT, ['cost' => 10]); $this->session->set('captcha', [ 'key' => $hash, ]); //加上这行代码,便于后续校验验证码 if(empty(cache($key))){ cache($key, $hash, 5*60); }else{ return $this->generate(); } //加上这行代码,便于后续校验验证码 return [ 'value' => $bag, 'key' => $hash, ]; } /** * 验证验证码是否正确 * @access public * @param string $code 用户验证码 * @return bool 用户验证码是否正确 */ public function checkApi(string $code): bool { if (!cache($code)) { return false; } $key = cache($code); $code = mb_strtolower($code, 'UTF-8'); $res = password_verify($code, $key); if ($res) { cache($code,NULL); } return $res; }
2022年06月27日
242 阅读
0 评论
0 点赞
1
2
...
4