首页
关于小站
朋友
壁纸
留言
时光之书
笔顺字帖
LayUI手册
Search
1
【PHP】PHPoffice/PHPSpreadsheet读取和写入Excel
1,673 阅读
2
【Layui】控制页面元素展示隐藏
1,520 阅读
3
【Git】No tracked branch configured for branch master or the branch doesn't exist.
1,460 阅读
4
【PHP】PHP实现JWT生成和验证
1,370 阅读
5
精准检测,助力社交管理 —— 微信好友检测服务来袭!
1,278 阅读
默认分类
PHP
ThinkPHP
Laravel
面向对象
设计模式
算法
基础
网络安全
Web
HTML
CSS
JavaScript
jQuery
Layui
VUE
uni-app
Database
MySQL
Redis
RabbitMQ
Nginx
Git
Linux
Soft Ware
Windows
网赚
Go
Docker
登录
Search
标签搜索
PHP
函数
方法
类
MySQL
ThinkPHP
JavaScript
OOP
Layui
Web
Server
Docker
Linux
PHPSpreadsheet
PHPoffice
Array
设计模式
Git
排序算法
基础
小破孩
累计撰写
244
篇文章
累计收到
13
条评论
首页
栏目
默认分类
PHP
ThinkPHP
Laravel
面向对象
设计模式
算法
基础
网络安全
Web
HTML
CSS
JavaScript
jQuery
Layui
VUE
uni-app
Database
MySQL
Redis
RabbitMQ
Nginx
Git
Linux
Soft Ware
Windows
网赚
Go
Docker
页面
关于小站
朋友
壁纸
留言
时光之书
笔顺字帖
LayUI手册
搜索到
59
篇与
的结果
2025-05-17
【ThinkPHP】创建有背景的微信小程序二维码
<?php namespace app\common\lib\wechat; use think\Exception; use think\facade\Cache; use think\facade\Request; use think\Image; use think\facade\Db; class QrCode extends Basic { // 小程序页面路径 private string $path = "pages/myCenter/invite"; // 小程序码保存路径 private string $savePath = "./storage/qrcode/"; // 二维码参数 private string $param = ""; public function __construct(string $path = "", string $field = "", string $param = "", int $width = 430) { if (!empty($path) && empty($field)) { $this->path = $path; } if (!empty($path) && !empty($field) && !empty($param)) { $this->path = "{$path}?{$field}={$param}"; } $this->param = $param; } /** * 生成小程序码并可选择合并背景图 * * @param string $backgroundPath 背景图路径 * @param int $qrWidth 二维码在背景图上的宽度位置 * @param int $qrHeight 二维码在背景图上的高度位置 * @return string 生成后的二维码URL */ public function setQrcode(string $backgroundPath = '', int $qrWidth = 160, int $qrHeight = 530): string { try { // 获取访问令牌 $accessToken = Cache::get('accesstoken'); if (empty($accessToken)) { $accessToken = (new AccessToken())->getAccesToken(); Cache::set('accesstoken', $accessToken, 7200); // 假设token有效期为2小时 } // 请求小程序码 $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}"; $data = [ 'path' => $this->path, 'scene' => 'type=qrcode', 'width' => 430, ]; $result = $this->curlPost($url, $data, 'POST'); if ($result === false || isset($result['errcode'])) { throw new Exception("Failed to get QR code: " . json_encode($result)); } // 保存二维码到文件 $fileName = md5($this->param); $directory = $this->savePath . date('Ymd') . '/'; if (!$this->createDirectory($directory)) { throw new Exception("目录创建失败: {$directory}"); } $filePath = "{$directory}{$fileName}.png"; if (!file_put_contents($filePath, $result)) { throw new Exception("文件写入失败: {$filePath}"); } // 生成完整URL $fullDomain = (new \app\common\lib\data\Str())->getFullDomain(); $qrcodeUrl = $fullDomain . ltrim($filePath, '.'); // 合并背景图(如果提供) if (!empty($backgroundPath)) { return $this->mergeWithBackground($backgroundPath, $filePath, $qrcodeUrl, $qrWidth, $qrHeight); } return $qrcodeUrl; } catch (Exception $e) { // 记录错误日志 error_log($e->getMessage()); return ''; } } /** * 将二维码与背景图合并 */ private function mergeWithBackground(string $backgroundPath, string $qrcodePath, string $defaultUrl, int $qrWidth, int $qrHeight): string { try { $fileName = md5(uniqid() . time()); $newImagePath = $this->savePath . date('Ymd') . "/{$fileName}.png"; $background = Image::open($backgroundPath); $background->water($qrcodePath, [$qrWidth, $qrHeight])->save($newImagePath); $imageInfo = [ 'url' => Request::domain() . substr($newImagePath, 1), 'size' => filesize($newImagePath), 'name' => $fileName, 'mime' => mime_content_type($newImagePath), 'ext' => 'png', ]; $fileData = [ 'f_uuid' => setUUID(), 'f_file' => $imageInfo['url'], 'f_location' => 0, 'f_type' => 'image', 'f_info' => serialize($imageInfo), 'f_user_uuid' => $this->request->index_user_uuid ?? '', 'f_create_time' => time(), ]; Db::name('File')->insert($fileData); return $imageInfo['url']; } catch (Exception $e) { // 记录错误日志 error_log($e->getMessage()); return $defaultUrl; } } /** * 递归创建目录 */ private function createDirectory(string $path, int $mode = 0777, bool $recursive = true): bool { if (is_dir($path)) { return true; } if (mkdir($path, $mode, $recursive)) { chmod($path, $mode); return true; } if (!is_dir(dirname($path))) { if ($this->createDirectory(dirname($path), $mode, $recursive)) { return $this->createDirectory($path, $mode, $recursive); } } return false; } /** * 发送HTTP POST请求 */ // public function curlPost($url, $data, $method = "POST") // { // $ch = curl_init(); //1.初始化 // curl_setopt($ch, CURLOPT_URL, $url); //2.请求地址 // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);//3.请求方式 // //4.参数如下 // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');//模拟浏览器 // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip, deflate'));//gzip解压内容 // curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); // // if ($method == "POST") {//5.post方式的时候添加数据 // $data = json_encode($data); // curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // } // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // $tmpInfo = curl_exec($ch);//6.执行 // // if (curl_errno($ch)) {//7.如果出错 // return curl_error($ch); // } // curl_close($ch);//8.关闭 // return $tmpInfo; // } }
2025年05月17日
15 阅读
0 评论
0 点赞
2025-05-07
【PHP】PHP实现无限级树形分类 树形分类 如果子集的pid不是空,父级id不存在,则子集不展示
/** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2024/12/17 22:27 * @param $arr * @param $id * @param $pid * @return array * @Description:树形分类 如果子集的pid不是空,父级id不存在,则子集不展示 */ public function getTreeByDateDelChile($arr,$id,$pid) { $items = []; foreach($arr as $v){ $items[$v[$id]] = $v; } $tree = []; foreach($items as $k => $item){ if($item[$pid] &&!isset($items[$item[$pid]])){ unset($items[$k]); continue; } if(isset($items[$item[$pid]])){ $items[$item[$pid]]['child'][] = &$items[$k]; }else{ $tree[] = &$items[$k]; } } return $tree; } /** * @Author:小破孩 * @Email:3584685883@qq.com * @Time:2024/9/14 16:59 * @param array $arr * @param string $children * @return array * @Description:将树形数组转换成一维数组 */ public function setManyTosingle(array $arr = [], string $children = 'child'): array { $result = []; foreach ($arr as $item) { // 先将当前节点添加到结果数组中 $newItem = $item; if (isset($newItem[$children])) { unset($newItem[$children]); } $result[] = $newItem; // 递归处理子节点 if (isset($item[$children]) && is_array($item[$children])) { $result = array_merge($result, $this->setManyTosingle($item[$children], $children)); } } return $result; }
2025年05月07日
19 阅读
0 评论
0 点赞
2025-05-06
【PHP】清空MySQL数据,索引重置
<?php // 定义排除表的常量 const EXCLUDE_TABLES = [ 'web_admin_company', 'web_admin_func', 'web_admin_role', 'web_admin_user', 'web_app_config', 'web_china_city', 'web_china_city_area', 'web_china_city_backup', 'web_company_config', 'web_shop_category', 'web_tppay', // 'web_shop_goods_tmpserver', ]; class SomeClass { public function truncateTables() { try { // 开启事务 Db::startTrans(); // 获取所有表名 $tables = Db::query('SHOW TABLES'); $tableNames = array_map('current', $tables); foreach ($tableNames as $tableName) { if (!in_array($tableName, EXCLUDE_TABLES)) { // 使用参数化查询清空表并重置索引 Db::execute("TRUNCATE TABLE `$tableName`"); echo "表 {$tableName} 已清空<br>"; } } // 提交事务 Db::commit(); } catch (\Exception $e) { // 回滚事务 Db::rollback(); // 记录错误日志 error_log("发生错误: " . $e->getMessage()); echo "发生错误: " . $e->getMessage(); } } }
2025年05月06日
17 阅读
0 评论
0 点赞
2025-04-23
【PHP】管家婆各个大类的基础调用数据方法
<?php namespace app\common\lib\gjp\warehouse; use think\Exception; class Warehouse { protected $dbName; public function __construct() { $this->dbName = "*****"; // } //查询单据 public function getWarehouse($paramkey = "", $paramJson = "", $userId = "***********")// { $instanceGjpBasic = new \app\common\lib\gjp\Basic(); $gjpSignInfo = $instanceGjpBasic->getSignKey(); $instanceGjpApiUrl = new \app\common\lib\gjp\Apiurl($userId); $gjpApiUrlInfo = $instanceGjpApiUrl -> getApiUrl(); $mobile = empty($gjpApiUrlInfo['GraspCloudMobile']) ? 0 : $gjpApiUrlInfo['GraspCloudMobile']; $serviceid = empty($gjpApiUrlInfo['GraspCloudServerId']) ? 0 : $gjpApiUrlInfo['GraspCloudServerId']; $requestUrl = $gjpApiUrlInfo['ApiServerAddress']; $md5BeforeStr = "apiparam".$gjpApiUrlInfo['ApiParam']."apitype".'query'."dbname".(string)$this->dbName."interiorapi"."1"."managename"."GraspCMServerApi.dll"."mobile".$mobile."paramjson".$paramJson."paramkey".$paramkey."serviceid".$serviceid.$gjpSignInfo['SignKey']; $data = [ 'managename' => (string)"GraspCMServerApi.dll", 'dbname' => (string)$this->dbName, 'paramkey' => (string)$paramkey, 'paramjson' => (string)($paramJson), 'apiparam' => (string)$gjpApiUrlInfo['ApiParam'], 'apitype' => (string)"query", 'sign' => (string)md5($md5BeforeStr), 'mobile' => (string)$mobile, 'serviceid' => (string)$serviceid, 'interiorapi' => (integer)1, ]; $encodedParams = http_build_query($data); $result = $instanceGjpBasic->curlRequest($requestUrl,"POST",$encodedParams,true,false); if($result['code'] != 0){ print_r($result);die; } return $result; } //生产单据 public function setReceipts($vchtype = 0,$billdata = '',$userId = "*************"){ $instanceGjpBasic = new \app\common\lib\gjp\Basic(); $gjpSignInfo = $instanceGjpBasic->getSignKey(); $instanceGjpApiUrl = new \app\common\lib\gjp\Apiurl($userId); $gjpApiUrlInfo = $instanceGjpApiUrl -> getApiUrl(); $requestUrl = $gjpApiUrlInfo['ApiServerAddress']; $mobile = empty($gjpApiUrlInfo['GraspCloudMobile']) ? 0 : $gjpApiUrlInfo['GraspCloudMobile']; $serviceid = empty($gjpApiUrlInfo['GraspCloudServerId']) ? 0 : $gjpApiUrlInfo['GraspCloudServerId']; $md5BeforeStr = "apiparam".$gjpApiUrlInfo['ApiParam']."apitype".'process'."billdata". $billdata ."dbname".(string)$this->dbName."interiorapi"."1"."managename"."GraspCMServerApi.dll"."mobile".$mobile."processtype"."0"."serviceid".$serviceid."vchcode"."0"."vchtype".$vchtype.$gjpSignInfo['SignKey']; $data = [ 'managename' => (string)"GraspCMServerApi.dll", 'dbname' => (string)$this->dbName, 'processtype' => (integer)0, 'vchtype' => (integer)$vchtype, 'vchcode' => (integer)0, 'billdata' => (string)$billdata, 'apiparam' => (string)$gjpApiUrlInfo['ApiParam'], 'apitype' => (string)"process", 'sign' => (string)md5($md5BeforeStr), 'mobile' => (string)$mobile, 'serviceid' => (string)$serviceid, 'interiorapi' => (integer)1, ]; // print_r($data);die; $encodedParams = http_build_query($data); $result = $instanceGjpBasic->curlRequest($requestUrl,"POST",$encodedParams,true,false); return $result; } //新增或修改 基础资料新增 public function businessBaseInfo($basetype = "", $baseinfodata = "", $rec = "", $type = 1, $userId = "*********"){ if($type == 1){ $typeName = "add"; }else{ $typeName = "modify"; } if(empty($rec)){ (string)$rec = "0"; } $instanceGjpBasic = new \app\common\lib\gjp\Basic(); $gjpSignInfo = $instanceGjpBasic->getSignKey(); $instanceGjpApiUrl = new \app\common\lib\gjp\Apiurl($userId); $gjpApiUrlInfo = $instanceGjpApiUrl -> getApiUrl(); // print_r($gjpApiUrlInfo);die; $mobile = empty($gjpApiUrlInfo['GraspCloudMobile']) ? 0 : $gjpApiUrlInfo['GraspCloudMobile']; $serviceid = empty($gjpApiUrlInfo['GraspCloudServerId']) ? 0 : $gjpApiUrlInfo['GraspCloudServerId']; $requestUrl = $gjpApiUrlInfo['ApiServerAddress']; $md5BeforeStr ="actiontype".$typeName."apiparam".$gjpApiUrlInfo['ApiParam']."apitype".'baseinfo'."baseinfodata".$baseinfodata."basetype".$basetype."dbname".(string)$this->dbName."interiorapi"."1"."managename"."GraspCMServerApi.dll"."mobile".$mobile."rec".$rec."serviceid".$serviceid.$gjpSignInfo['SignKey']; // "actiontype".$typeName."apiparam".$gjpApiUrlInfo['ApiParam']."apitype"."baseinfo"."basetype".$basetype."baseinfodata".$baseinfodata."dbname".$this->dbName."interiorapi".1."managename"."GraspCMServerApi.dll"."mobile".$mobile."serviceid".$serviceid."sign".md5($md5BeforeStr) $data = [ 'managename' => (string)"GraspCMServerApi.dll", 'dbname' => (string)$this->dbName, 'actiontype' => (string)$typeName, 'rec' => (string)$rec, 'basetype' => (string)$basetype, 'baseinfodata' => (string)$baseinfodata, 'apiparam' => (string)$gjpApiUrlInfo['ApiParam'], 'apitype' => (string)"baseinfo", 'sign' => (string)md5($md5BeforeStr), 'mobile' => (string)$mobile, 'serviceid' => (string)$serviceid, 'interiorapi' => (integer)1, ]; $encodedParams = http_build_query($data); $result = $instanceGjpBasic->curlRequest($requestUrl,"POST",$encodedParams,true,false); if($result['code'] != 0){ print_r($result);die; } return $result; } }
2025年04月23日
17 阅读
0 评论
0 点赞
2025-04-23
【PHP】获取程序Api地址 - 管家婆基础对接 PHP版本
<?php namespace app\common\lib\gjp; class Apiurl { protected $userId; protected $appKey; protected $SercretKey; protected $currentTimestamp; protected $dbName; public function __construct($userId = '********') { $this->appKey = "*****************"; $this->SercretKey = "*******************"; $this->currentTimestamp = time(); $this->userId = $userId; $this->dbName = '*****'; } public function getApiUrl() { $url = "http://api.cmgrasp.com/CMGraspApi/GateWay"; $instanceGjpBasic = new \app\common\lib\gjp\Basic(); $instanceStr = new \app\common\lib\data\Str(); $randamStr = $instanceStr->setNonce(32,true); $md5BeforeStr = "AppKey".$this->appKey."InvalidTime".date('YmdHis',$this->currentTimestamp)."RandamStr".$randamStr."UserId".$this->userId.$this->SercretKey; $data = [ 'MethodName' => (string)"graspcm.cmapi.getcustomerapiurl", 'AppKey' => (string)$this->appKey, 'UserId' => (string)$this->userId, 'InvalidTime' => (string)date('Y-m-d H:i:s'), 'RandamStr' => (string)$randamStr, 'SignStr' => (string)md5($md5BeforeStr), 'DbName' => (string)$this->dbName ]; $jsonData = json_encode($data); $result = $instanceGjpBasic->curlRequest($url,"POST",$jsonData,true,false); if($result['RetCode'] != 0){ $this->getApiUrl(); } $resultData = json_decode($result['RetMsg'],true); return $resultData; } }
2025年04月23日
15 阅读
0 评论
0 点赞
2025-04-23
【PHP】获取接口所需的SignKey - 管家婆基础对接 PHP版本
<?php namespace app\common\lib\gjp; use think\Exception; class Basic { protected $appKey; protected $SercretKey; protected $currentTimestamp; public function __construct() { $this->appKey = "*************"; $this->SercretKey = "*************"; $this->currentTimestamp = time(); } public function getSignKey() { if(!empty( cache('gjp_sign'))) { $dataResult = cache('gjp_sign'); return $dataResult; } $signUrl = "http://api.cmgrasp.com/CMGraspApi/GateWay"; $instanceStr = new \app\common\lib\data\Str(); $randamStr = $instanceStr->setNonce(32,true); $md5BeforeStr = "AppKey".$this->appKey."InvalidTime".date('YmdHis',$this->currentTimestamp)."RandamStr".$randamStr.$this->SercretKey; $data = [ "MethodName" => (string)"graspcm.cmapi.getsignstr", 'AppKey' => (string)$this->appKey, 'InvalidTime' => (string)date('Y-m-d H:i:s',$this->currentTimestamp), 'RandamStr' => (string)$randamStr, 'SignStr' => (string)md5($md5BeforeStr), ]; $jsonData = json_encode($data); $result = $this->curlRequest($signUrl,"POST", $jsonData,true,false); if($result['RetCode'] != 0) { $this->getSignKey(); } $dataResult = json_decode($result['RetMsg'],true); if(empty( cache('gjp_sign'))) { $dataResult = json_decode($result['RetMsg'],true); cache('gjp_sign',$dataResult,60*60*20); } return $dataResult; } /** * @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请求 */ public 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; } }
2025年04月23日
14 阅读
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日
54 阅读
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日
358 阅读
0 评论
0 点赞
2022-11-03
【ThinkPHP】tp6获取应用名
protected $filter = ['htmlspecialchars']; public function app_name() { return App('http')->getName(); }
2022年11月03日
324 阅读
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日
342 阅读
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日
316 阅读
0 评论
0 点赞
2022-06-27
【PHP】删除数组指定的键
/** * php除数组指定的key值(直接删除key值实现) * @param unknown $data * @param unknown $key * @return unknown */ function array_remove($data, $key){ if(!array_key_exists($key, $data)){ return $data; } $keys = array_keys($data); $index = array_search($key, $keys); if($index !== FALSE){ array_splice($data, $index, 1); } return $data; } /** * php除数组指定的key值(通过直接重新组装一个数组) * @param unknown $data * @param unknown $key * @return unknown */ function array_remove1($data,$delKey) { $newArray = array(); if(is_array($data)) { foreach($data as $key => $value) { if($key !== $delKey) { $newArray[$key] = $value; } } }else { $newArray = $data; } return $newArray; } $data = array('apple','address','ChinaGuangZhou'); $result = array_remove($data, 'name'); $result1 = array_remove1($data, 'name'); print_r($result); print_r($result1);
2022年06月27日
348 阅读
0 评论
0 点赞
2022-06-25
【PHP】PHP实现网络请求的方法及函数总结
一、分析php发送网网络请求的方法对于php发送网络请求,我们最常用的请求就是curl,有时我们也会用到file_get_contents函数发送网络请求,但file_get_contents只能完成一些间单的网络请求,稍复杂的就无法完成,例如文件上传,cookies,验证,表单提交等,用php的curl可以使用URL的语法模拟浏览器来传输数据,因为它是模拟浏览器,因此它同样支持多种协议,FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP等协议都可以很好的支持,包括一些:HTTPS认证,HTTP POST方法,HTTP PUT方法,FTP上传,keyberos认证,HTTP上传,代理服务器,cookies,用户名/密码认证,下载文件断点续传,上传文件断点续传,http代理服务器管道,甚至它还支持IPv6,scoket5代理服务器,通过http代理服务器上传文件到FTP服务器等等,所以我们在开发中尽量用curl发网络请求,无论是简单还是复杂二、file_get_contents发送网络请求示例file_get_contents(path,include_path,context,start,max_length)一般用file_get_contents或者fopen, file , readfile等函数读取url的时候 会创建一个$http_response_header变量保存HTTP响应的报头,使用fopen等函数打开的数据流信息可以用stream_get_meta_data获取$html = file_get_contents('http://www.baidu.com'); print_r($http_response_header); $fp = fopen('http://www.baidu.com', 'r'); print_r(stream_get_meta_data($fp)); fclose($fp);摸拟post请求:$url = 'http://192.168.1.1/test.php'; $data = array( 'keyword' => 'test data', ); $content = http_build_query($data); $content_length = strlen($content); $options = array( 'http' => array( 'method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-length: $content_length\r\n", 'content' => $content ) ); echo file_get_contents($url, false, stream_context_create($options));三、php 用curl发送网络请求curl可以支持https认证、http post、ftp上传、代理、cookies、简单口令认证等等功能,使用前需要先在你的PHP环境中安装和启用curl模块,这里有两种写法供大家参考:<?php function geturl($url){ $headerArray =array("Content-type:application/json;","Accept:application/json"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray); $output = curl_exec($ch); curl_close($ch); $output = json_decode($output,true); return $output; } function posturl($url,$data){ $data = json_encode($data); $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json"); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return json_decode($output,true); } function puturl($url,$data){ $data = json_encode($data); $ch = curl_init(); //初始化CURL句柄 curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出 curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串 $output = curl_exec($ch); curl_close($ch); return json_decode($output,true); } function delurl($url,$data){ $data = json_encode($data); $ch = curl_init(); curl_setopt ($ch,CURLOPT_URL,$put_url); curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json')); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_POSTFIELDS,$data); $output = curl_exec($ch); curl_close($ch); $output = json_decode($output,true); } function patchurl($url,$data){ $data = json_encode($data); $ch = curl_init(); curl_setopt ($ch,CURLOPT_URL,$url); curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json')); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_POSTFIELDS,$data); //20170611修改接口,用/id的方式传递,直接写在url中了 $output = curl_exec($ch); curl_close($ch); $output = json_decode($output); return $output; } ?>一个函数片时各种请求:function sendCurl($url, $data = null,$method='POST') { $method=strtoupper($method); $start_wdmcurl_time = microtime(true); $header = array(' application/x-www-form-urlencoded'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); // https 请求 if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if($method=='GET'){ if($data && is_array($data) && count($data)>0 ){ $url.="?".http_build_query($data); } curl_setopt($ch, CURLOPT_URL, $url); }elseif($method=='POST'){ curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); if (is_array($data) && count($data)>0) { curl_setopt($ch, CURLOPT_POST, true); $isPostMultipart = false; foreach ($data as $k => $v) { if ('@' == substr($v, 0, 1)) { $isPostMultipart = true; break; } } unset($k, $v); if ($isPostMultipart) { curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); } } }elseif(in_array($method,['PUT','DELETE','PATCH'])){ curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_HTTPHEADER,$header); $reponse = curl_exec($ch); curl_close($ch); return $reponse; }四、使用php composer的扩展guzzlehttpcomposer require guzzlehttp/guzzle $client = new \GuzzleHttp\Client(); $response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); echo $response->getStatusCode(); // 200 echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' // Send an asynchronous request. $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); $promise = $client->sendAsync($request)->then(function ($response) { echo 'I completed! ' . $response->getBody(); }); $promise->wait();日常开发中我们尽量用方法三,自定义用curl处理网络请求,或用composer的guzzlehttp扩展库,有起来也很方便。学习地址:https://mp.weixin.qq.com/s/MOQyelYTv_UYYx9dqIOVRw
2022年06月25日
305 阅读
0 评论
0 点赞
2022-06-23
【PHP】ThinkPHP6 公共 上传到本地的方法 附带使用方法
<?php namespace app\common\lib\files; use think\Exception; use think\exception\ValidateException; class upload { private $domain; protected $name; protected $type; protected $module; protected $image; public function __construct($name = '',$type = 'image',$image = []) { $this->name = $name; $this->type = $this->checkUpload($type); $this->module = request()->app_name(); $this->image = $image; $this->domain = Request()->domain(); } protected $config = [ 'image' => [ 'validate' => [ 'size' => 10*1024*1024, 'ext' => 'jpg,png,gif,jpeg', ], 'path' => '/images', ], 'audio' => [ 'validate' => [ 'size' => 100*1024*1024, 'ext' => 'mp3,wav,cd,ogg,wma,asf,rm,real,ape,midi', ], 'path' => '/audios', ], 'video' => [ 'validate' => [ 'size' => 100*1024*1024, 'ext' => 'mp4,avi,rmvb,rm,mpg,mpeg,wmv,mkv,flv', ], 'path' => '/videos', ], 'file' => [ 'validate' => [ 'size' => 5*1024*1024, 'ext' => 'doc,docx,xls,xlsx,pdf,ppt,txt,rar,zip,pem,p12', ], 'path' => '/files', ], ]; private function checkUpload($type){ try{ if(empty($_FILES) || empty($_FILES[$this->name])) throw new Exception("未上传文件!"); if(!in_array($type,array_keys($this->config))) throw new Exception("文件类型不存在!"); return $type; }catch (Exception $e){ return \app\common\controller\Base::show(100,$e->getMessage()); } } public function upfile($infoSwitch = false){ $file = request()->file($this->name); try{ if($file == null) throw new ValidateException("the file cannot be empty"); validate(['file' => self::validateFile()])->check(['file' => $file]); $savename = \think\facade\Filesystem::disk('public')->putFile( $this->module.$this->config[$this->type]['path'], $file); if($infoSwitch){ return self::getFileInfo($file,$savename); } return $savename; }catch (\think\exception\ValidateException $e){ return \app\common\controller\Base::show(100,self::languageChange($e->getMessage())); } } private function validateFile(){ if(empty($this->image)){ $validataType = [ 'fileSize' => $this->config[$this->type]['validate']['size'], 'fileExt' => $this->config[$this->type]['validate']['ext'], ]; }else{ if(is_array($this->image)) throw new ValidateException(""); $validataType = [ 'fileSize' => $this->config[$this->type]['validate']['size'], 'fileExt' => $this->config[$this->type]['validate']['ext'], 'image' => $this->image //示例值 [200,200] ]; } return $validataType; } private function languageChange($msg){ $data = [ 'the file cannot be empty' => '文件不能为空!', 'unknown upload error' => '未知上传错误!', 'file write error' => '文件写入失败!', 'upload temp dir not found' => '找不到临时文件夹!', 'no file to uploaded' => '没有文件被上传!', 'only the portion of file is uploaded' => '文件只有部分被上传!', 'upload File size exceeds the maximum value' => '上传文件大小超过了最大值!', 'upload write error' => '文件上传保存错误!', ]; return $data[$msg] ?? $msg; } private function getFileInfo($file,$savename){ $info = [ 'path' => config('filesystem.disks.public.url').'/'.str_replace('\\','/',$savename), 'url' => $this->domain.config('filesystem.disks.public.url').'/'.str_replace('\\','/',$savename), 'size' => $file->getSize(), 'name' => $file->getOriginalName(), 'mime' => $file->getMime(), 'ext' => $file->extension() ]; return $info; } } > 使用方法 : > > $instanceUpload = new upload($fileName,$fileType); > $info = $instanceUpload->upfile(true);
2022年06月23日
245 阅读
0 评论
0 点赞
2022-06-23
【PHP】PHP快速读取大文件指定行的方法
1、面临问题分析读取普通小文件我们一般用fopen 或者 file_get_contents就很方便简单 ,前者可以循环读取,后者可以一次性读取,但都是将文件内容一次性加载来操作。如果加载的文件特别大时,如几百M、上G时,这时性能贫瘠就非常突出了,那么PHP里有没有对大文件的处理函数或者类呢? 答案是:有的。2、SplFileObject类高效解决大文件读取问题从 PHP 5.1.0 开始,SPL 库增加了 SplFileObject 与 SplFileInfo 两个标准的文件操作类。从字面意思理解看,可以看出 SplFileObject 要比 SplFileInfo 更为强大。不错,SplFileInfo 仅用于获取文件的一些属性信息,如文件大小、文件访问时间、文件修改时间、后缀名等值,而 SplFileObject 是继承 SplFileInfo 这些功能并新增很多文件处理类操作方法的一个文件操作类。 /** 返回文件从X行到Y行的内容(支持php5、php4) * @param string $filename 文件名 * @param int $startLine 开始的行数 * @param int $endLine 结束的行数 * @return string */ function getFileLines($filename, $startLine = 1, $endLine=50, $method='rb') { $content = array(); $count = $endLine - $startLine; // 判断php版本(因为要用到SplFileObject,PHP>=5.1.0) if(version_compare(PHP_VERSION, '5.1.0', '>=')){ $fp = new SplFileObject($filename, $method); $fp->seek($startLine-1);// 转到第N行, seek方法参数从0开始计数 for($i = 0; $i <= $count; ++$i) { $content[]=$fp->current();// current()获取当前行内容 $fp->next();// 下一行 } }else{//PHP<5.1 $fp = fopen($filename, $method); if(!$fp) return 'error:can not read file'; for ($i=1;$i<$startLine;++$i) {// 跳过前$startLine行 fgets($fp); } for($i;$i<=$endLine;++$i){ $content[]=fgets($fp);// 读取文件行内容 } fclose($fp); } return array_filter($content); // array_filter过滤:false,null,'' }Ps:(1)、上面都没加”读取到末尾的判断”:!$fp->eof() 或者 !feof($fp),结果实践加上这个判断影响效率,而且这里加上也完全没必要。(2)、从上面的函数和实践操作就可以看出来使用SplFileObject类比下面的fgets函数效率要高很多,特别是文件行数非常多、并且要取越后面的内容的时候。fgets要两个循环才可以。
2022年06月23日
1,025 阅读
0 评论
0 点赞
2022-06-23
【PHP】PHP读取文件指定行的内容
function getLine($file, $line, $length = 40960){ $returnTxt = null; // 初始化返回 $i = 1; // 行数 $handle = @fopen($file, "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, $length); if($line == $i) $returnTxt = $buffer; $i++; } fclose($handle); } return $returnTxt; }
2022年06月23日
280 阅读
0 评论
0 点赞
2022-06-23
【PHP】ThinkPHP 5.1公共上传类
<?php namespace app\extra; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //适配移动设备图片上传 use think\Exception; use think\facade\Request; class ExtraUpload{ /** * 默认上传配置 * @var array */ private $config = [ 'image' => [ 'validate' => [ 'size' => 10*1024*1024, 'ext' => 'jpg,png,gif,jpeg', ], 'rootPath' => './Uploads/images/', //保存根路径 ], 'audio' => [ 'validate' => [ 'size' => 100*1024*1024, 'ext' => 'mp3,wav,cd,ogg,wma,asf,rm,real,ape,midi', ], 'rootPath' => './Uploads/audios/', //保存根路径 ], 'video' => [ 'validate' => [ 'size' => 100*1024*1024, 'ext' => 'mp4,avi,rmvb,rm,mpg,mpeg,wmv,mkv,flv', ], 'rootPath' => './Uploads/videos/', //保存根路径 ], 'file' => [ 'validate' => [ 'size' => 5*1024*1024, 'ext' => 'doc,docx,xls,xlsx,pdf,ppt,txt,rar', ], 'rootPath' => './Uploads/files/', //保存根路径 ], ]; private $domain; function __construct() { //获取当前域名 $this->domain = Request::instance()->domain(); } public function upload($fileName){ if(empty($_FILES) || empty($_FILES[$fileName])){ // return ''; returnResponse(100,'文件为空'); } try{ $file = request()->file($fileName); if (is_array($file)){ $path = []; foreach ($file as $item){ $path[] = $this->save($item); } } else { $path = $this->save($file); } return $path; } catch (\Exception $e){ $arr = [ 'status' => 0, 'message' => $e->getMessage(), ]; header('Content-Type: application/json; charset=UTF-8'); exit(json_encode($arr)); } } public function uploadDetail($fileName){ if(empty($_FILES) || empty($_FILES[$fileName])){ // return []; returnResponse(100,'文件为空'); } try{ $file = request()->file($fileName); if (is_array($file)){ $path = []; foreach ($file as $item){ $detail = $item->getInfo(); $returnData['name'] = $detail['name']; $returnData['type'] = $detail['type']; $returnData['size'] = $detail['size']; $returnData['filePath'] = $this->save($item); $returnData['fullPath'] = $this->domain.$returnData['filePath']; $path[] = $returnData; } } else { $detail = $file->getInfo(); $returnData['name'] = $detail['name']; $returnData['type'] = $detail['type']; $returnData['size'] = $detail['size']; $returnData['filePath'] = $this->save($file); $returnData['fullPath'] = $this->domain.$returnData['filePath']; $path = $returnData; } return $path; } catch (\Exception $e){ $arr = [ 'status' => 0, 'message' => $e->getMessage(), ]; header('Content-Type: application/json; charset=UTF-8'); exit(json_encode($arr)); } } private function getConfig($file){ $name = pathinfo($file['name']); $end = $name['extension']; foreach ($this->config as $key=>$item){ if ($item['validate']['ext'] && strpos($item['validate']['ext'], $end) !== false){ return $this->config[$key]; } } return null; } private function save(&$file){ $config = $this->getConfig($file->getInfo()); if (empty($config)){ throw new Exception('上传文件类型不被允许!'); } // 移动到框架应用根目录/uploads/ 目录下 if ($config['validate']) { $file->validate($config['validate']); $result = $file->move($config['rootPath']); } else { $result = $file->move($config['rootPath']); } if($result){ $path = $config['rootPath']; if (strstr($path,'.') !== false){ $path = str_replace('.', '', $path); } return $path.$result->getSaveName(); }else{ // 上传失败获取错误信息 throw new Exception($file->getError()); } } } 使用方法: $p = new \app\extra\ExtraUpload(); return $p->uploadDetail('file');
2022年06月23日
359 阅读
0 评论
0 点赞
2022-06-23
【PHP】PHP实现批量修改图片名称
<?php // glob() 返回指定目录下的文件名以及目录 $arr = glob("blog.8688pic.com/*.JPG"); $i = 1; // 循环遍历 foreach($arr as $file) { // 获取图片后缀名 $ext = pathinfo($file,PATHINFO_EXTENSION); // 确定图片的新名字 $name = $i++ . "." . 'jpg'; // 重命名 rename($file, $name); } die(); ?>
2022年06月23日
243 阅读
0 评论
0 点赞
2022-06-23
【PHP】PHP随机生成字符串
public function setRandomString($len = 32) { $string = ''; $char = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; for ($i = 0; $i < $len; $i++) { $string .= $char[mt_rand(0, strlen($char) - 1)]; } return $string; }
2022年06月23日
255 阅读
0 评论
0 点赞
2022-06-23
【PHP】获取字符串的两个字符中间的内容
/** * Author: 小破孩 * Email: 3584685883@qq.com * Time: 2022/2/14 16:12 * @param $str * @param $separator * @param string $mark * @return bool|false|mixed|string * Description:获取字符串 */ public function getSubStr($str,$separator,$mark=':'){ $arr = explode($separator,$str); if (empty($arr) || !isset($arr[1])) { return false; } $str = $arr[1]; if (strpos($str,$mark) !== false) { return substr($str,0,strpos($str,$mark)); }else{ return $str; } }
2022年06月23日
351 阅读
0 评论
0 点赞
1
2
3