首页
关于
归档
朋友
壁纸
留言
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,039 阅读
3
【Layui】控制页面元素展示隐藏
860 阅读
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手册
搜索到
219
篇与
的结果
2022-08-02
【设计模式】装饰器模式
使用场景: 当某一功能或方法draw,要满足不同的功能需求时,可以使用装饰器模式;实现方式:在方法的类中建addDecorator(添加装饰器),beforeDraw,afterDraw 3个新方法, 后2个分别放置在要修改的方法draw首尾.然后创建不同的装器类(其中要包含相同的,beforeDraw,afterDraw方法)能过addDecorator添加进去,然后在beforeDraw,afterDraw中循环处理,与观察者模式使用有点相似1.装饰器模式(Decorator),可以动态地添加修改类的功能2.一个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程模式,需要写一个子类继承它,并重新实现类的方法3.使用装饰器模式,仅需在运行时添加一个装饰器对象即可实现,可以实现最大的灵活性DrawDecorator.php <?php namespace IMooc; interface DrawDecorator { function beforeDraw(); function afterDraw(); } Canvas.php<?php namespace IMooc; class Canvas { public $data; protected $decorators = array(); //Decorator function init($width = 20, $height = 10) { $data = array(); for($i = 0; $i < $height; $i++) { for($j = 0; $j < $width; $j++) { $data[$i][$j] = '*'; } } $this->data = $data; } function addDecorator(DrawDecorator $decorator) { $this->decorators[] = $decorator; } function beforeDraw() { foreach($this->decorators as $decorator) { $decorator->beforeDraw(); } } function afterDraw() { $decorators = array_reverse($this->decorators); foreach($decorators as $decorator) { $decorator->afterDraw(); } } function draw() { $this->beforeDraw(); foreach($this->data as $line) { foreach($line as $char) { echo $char; } echo "<br />\n"; } $this->afterDraw(); } function rect($a1, $a2, $b1, $b2) { foreach($this->data as $k1 => $line) { if ($k1 < $a1 or $k1 > $a2) continue; foreach($line as $k2 => $char) { if ($k2 < $b1 or $k2 > $b2) continue; $this->data[$k1][$k2] = ' '; } } } } ColorDrawDecorator.php<?php namespace IMooc; class ColorDrawDecorator implements DrawDecorator { protected $color; function __construct($color = 'red') { $this->color = $color; } function beforeDraw() { echo "<div style='color: {$this->color};'>"; } function afterDraw() { echo "</div>"; } } index.php<?php define('BASEDIR', __DIR__); include BASEDIR.'/IMooc/Loader.php'; spl_autoload_register('\\IMooc\\Loader::autoload'); $canvas = new IMooc\Canvas(); $canvas->init(); $canvas->addDecorator(new \IMooc\ColorDrawDecorator('green')); $canvas->rect(3,6,4,12); $canvas->draw();
2022年08月02日
261 阅读
0 评论
0 点赞
2022-08-02
【设计模式】策略模式
将一组特定的行为和算法封装成类,以适应某些特定的上下文环境。使用场景: 个人理解,策略模式是依赖注入,控制反转的基础例如:一个电商网站系统,针对男性女性用户要各自跳转到不同的商品类目,并且所有广告位展示不同的广告MaleUserStrategy.php<?php namespace IMooc; class MaleUserStrategy implements UserStrategy { function showAd() { echo "IPhone6"; } function showCategory() { echo "电子产品"; } } FemaleUserStrategy.php<?php namespace IMooc; class FemaleUserStrategy implements UserStrategy { function showAd() { echo "2014新款女装"; } function showCategory() { echo "女装"; } } UserStrategy.php<?php namespace IMooc; interface UserStrategy { function showAd(); function showCategory(); } <?php interface FlyBehavior{ public function fly(); } class FlyWithWings implements FlyBehavior{ public function fly(){ echo "Fly With Wings \n"; } } class FlyWithNo implements FlyBehavior{ public function fly(){ echo "Fly With No Wings \n"; } } class Duck{ private $_flyBehavior; public function performFly(){ $this->_flyBehavior->fly(); } public function setFlyBehavior(FlyBehavior $behavior){ $this->_flyBehavior = $behavior; } } class RubberDuck extends Duck{ } // Test Case $duck = new RubberDuck(); /* 想让鸭子用翅膀飞行 */ $duck->setFlyBehavior(new FlyWithWings()); $duck->performFly(); /* 想让鸭子不用翅膀飞行 */ $duck->setFlyBehavior(new FlyWithNo()); $duck->performFly();
2022年08月02日
234 阅读
0 评论
0 点赞
2022-08-02
【设计模式】适配器模式
将一个类的接口转换成客户希望的另一个接口,适配器模式使得原本的由于接口不兼容而不能一起工作的那些类可以一起工作。应用场景: 老代码接口不适应新的接口需求,或者代码很多很乱不便于继续修改,或者使用第三方类库。例如:php连接数据库的方法:mysql,,mysqli,pdo,可以用适配器统一//老的代码 class User { private $name; function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } //新代码,开放平台标准接口 interface UserInterface { function getUserName(); } class UserInfo implements UserInterface { protected $user; function __construct($user) { $this->user = $user; } public function getUserName() { return $this->user->getName(); } } $olduser = new User('张三'); echo $olduser->getName()."n"; $newuser = new UserInfo($olduser); echo $newuser->getUserName()."n";
2022年08月02日
232 阅读
0 评论
0 点赞
2022-08-02
【设计模式】观察者设计模式
观察者模式是挺常见的一种设计模式,使用得当会给程序带来非常大的便利,使用得不当,会给后来人一种难以维护的想法。使用场景: 用户登录,需要写日志,送积分,参与活动 等使用消息队列,把用户和日志,积分,活动之间解耦合什么是观察者模式? 一个对象通过提供方法允许另一个对象即观察者 注册自己)使本身变得可观察。当可观察的对象更改时,它会将消息发送到已注册的观察者。这些观察者使用该信息执行的操作与可观察的对象无关。结果是对象可以相互对话,而不必了解原因。观察者模式是一种事件系统,意味着这一模式允许某个类观察另一个类的状态,当被观察的类状态发生改变的时候,观察类可以收到通知并且做出相应的动作;观察者模式为您提供了避免组件之间紧密耦。看下面例子你就明白了!<?php /* 观察者接口 */ interface InterfaceObserver { function onListen($sender, $args); function getObserverName(); } // 可被观察者接口 interface InterfaceObservable { function addObserver($observer); function removeObserver($observer_name); } // 观察者抽象类 abstract class Observer implements InterfaceObserver { protected $observer_name; function getObserverName() { return $this->observer_name; } function onListen($sender, $args) { } } // 可被观察类 abstract class Observable implements InterfaceObservable { protected $observers = array(); public function addObserver($observer) { if ($observerinstanceofInterfaceObserver) { $this->observers[] = $observer; } } public function removeObserver($observer_name) { foreach ($this->observersas $index => $observer) { if ($observer->getObserverName() === $observer_name) { array_splice($this->observers, $index, 1); return; } } } } // 模拟一个可以被观察的类 class A extends Observable { public function addListener($listener) { foreach ($this->observersas $observer) { $observer->onListen($this, $listener); } } } // 模拟一个观察者类 class B extends Observer { protected $observer_name = 'B'; public function onListen($sender, $args) { var_dump($sender); echo "<br>"; var_dump($args); echo "<br>"; } } // 模拟另外一个观察者类 class C extends Observer { protected $observer_name = 'C'; public function onListen($sender, $args) { var_dump($sender); echo "<br>"; var_dump($args); echo "<br>"; } } $a = new A(); // 注入观察者 $a->addObserver(new B()); $a->addObserver(new C()); // 可以看到观察到的信息 $a->addListener('D'); // 移除观察者 $a->removeObserver('B'); // 打印的信息: // object(A)#1 (1) { ["observers":protected]=> array(2) { [0]=> object(B)#2 (1) { ["observer_name":protected]=> string(1) "B" } [1]=> object(C)#3 (1) { ["observer_name":protected]=> string(1) "C" } } } // string(1) "D" // object(A)#1 (1) { ["observers":protected]=> array(2) { [0]=> object(B)#2 (1) { ["observer_name":protected]=> string(1) "B" } [1]=> object(C)#3 (1) { ["observer_name":protected]=> string(1) "C" } } } // string(1) "D"
2022年08月02日
159 阅读
0 评论
0 点赞
2022-08-02
【设计模式】工厂设计模式
要是当操作类的参数变化时,只用改相应的工厂类就可以工厂设计模式常用于根据输入参数的不同或者应用程序配置的不同来创建一种专门用来实例化并返回其对应的类的实例。使用场景 :使用方法 new实例化类,每次实例化只需调用工厂类中的方法实例化即可。优点 :由于一个类可能会在很多地方被实例化。当类名或参数发生变化时,工厂模式可简单快捷的在工厂类下的方法中 一次性修改,避免了一个个的去修改实例化的对象。我们举例子,假设矩形、圆都有同样的一个方法,那么我们用基类提供的API来创建实例时,通过传参数来自动创建对应的类的实例,他们都有获取周长和面积的功能。例子<?php interface InterfaceShape { function getArea(); function getCircumference(); } /** * 矩形 */ class Rectangle implements InterfaceShape { private $width; private $height; public function __construct($width, $height) { $this->width = $width; $this->height = $height; } public function getArea() { return $this->width* $this->height; } public function getCircumference() { return 2 * $this->width + 2 * $this->height; } } /** * 圆形 */ class Circle implements InterfaceShape { private $radius; function __construct($radius) { $this->radius = $radius; } public function getArea() { return M_PI * pow($this->radius, 2); } public function getCircumference() { return 2 * M_PI * $this->radius; } } /** * 形状工厂类 */ class FactoryShape { public static function create() { switch (func_num_args()) { case1: return newCircle(func_get_arg(0)); case2: return newRectangle(func_get_arg(0), func_get_arg(1)); default: # code... break; } } } $rect =FactoryShape::create(5, 5); // object(Rectangle)#1 (2) { ["width":"Rectangle":private]=> int(5) ["height":"Rectangle":private]=> int(5) } var_dump($rect); echo "<br>"; // object(Circle)#2 (1) { ["radius":"Circle":private]=> int(4) } $circle =FactoryShape::create(4); var_dump($circle);
2022年08月02日
277 阅读
0 评论
0 点赞
2022-08-02
【设计模式】单例设计模式(Singleton)
所谓单例模式,即在应用程序中最多只有该类的一个实例存在,一旦创建,就会一直存在于内存中!应用场景: 单例设计模式常应用于数据库类设计,采用单例模式,只连接一次数据库,防止打开多个数据库连接。一个单例类应具备以下特点: 单例类不能直接实例化创建,而是只能由类本身实例化。因此,要获得这样的限制效果,构造函数必须标记为private,从而防止类被实例化。需要一个私有静态成员变量来保存类实例和公开一个能访问到实例的公开静态方法。在PHP中,为了防止他人对单例类实例克隆,通常还为其提供一个空的私有__clone()方法。单例模式的例子:<?php /** * Singleton of Database */ class Database { // We need a static private variable to store a Database instance. privatestatic $instance; // Mark as private to prevent it from being instanced. private function__construct() { // Do nothing. } private function__clone() { // Do nothing. } public static function getInstance() { if (!(self::$instance instanceof self)) { self::$instance = new self(); } return self::$instance; } } $a =Database::getInstance(); $b =Database::getInstance(); // true var_dump($a === $b);
2022年08月02日
219 阅读
0 评论
0 点赞
2022-08-02
【设计模式】设计模式六大原则
设计模式六大原则开放封闭原则 :一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。里氏替换原则 :所有引用基类的地方必须能透明地使用其子类的对象.依赖倒置原则 :高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。单一职责原则 :不要存在多于一个导致类变更的原因。通俗的说,即一个类只负责一项职责。接口隔离原则 :客户端不应该依赖它不需要的接口;一个类对另一个类的依赖应该建立在最小的接口上。迪米特法则 :一个对象应该对其他对象保持最少的了解。
2022年08月02日
521 阅读
1 评论
0 点赞
2022-07-25
【Windows】host文件路径
C:\Windows\System32\drivers\etc
2022年07月25日
192 阅读
0 评论
0 点赞
2022-07-15
【网赚】支付宝扫码
暂无简介
2022年07月15日
204 阅读
0 评论
0 点赞
2022-07-14
【Linux】使用Linux的Crontab定时执行PHP脚本
首先说说cron,它是一个linux下的定时执行工具根用户以外的用户可以使用 crontab 工具来配置 cron 任务。所有用户定义的 crontab 都被保存在/var/spool/cron 目录中,并使用创建它们的用户身份来执行。要以某用户身份创建一个 crontab 项目,登录为该用户,然后键入 crontab -e 命令来编辑该用户的 crontab。该文件使用的格式和 /etc/crontab 相同。当对 crontab 所做的改变被保存后,该 crontab 文件就会根据该用户名被保存,并写入文件 /var/spool/cron/username 中。cron 守护进程每分钟都检查 /etc/crontab 文件、etc/cron.d/ 目录、以及 /var/spool/cron 目录中的改变。如果发现了改变,它们就会被载入内存。这样,当某个 crontab 文件改变后就不必重新启动守护进程了。安装crontab:yum install crontabs说明:/sbin/service crond start //启动服务 /sbin/service crond stop //关闭服务 /sbin/service crond restart //重启服务 /sbin/service crond reload //重新载入配置 查看crontab服务状态:service crond status 手动启动crontab服务:service crond start 查看crontab服务是否已设置为开机启动,执行命令:ntsysv加入开机自动启动: chkconfig –level 35 crond on 每一小时执行myscript.php如下:# crontab -e 00 * * * * /usr/local/bin/php /home/john/myscript.php如果你的PHP脚本可以通过URL触发,你可以使用lynx或curl或wget来配置你的Crontab。 下面的例子是使用Lynx文本浏览器访问URL来每小时执行PHP脚本。Lynx文本浏览器默认使用对话方式打开URL。但是,像下面的,我们在lynx命令行中使用-dump选项来把URL的输出转换来标准输出。 00 * * * * lynx -dump http://www.jb51.net/myscript.php 下面的例子是使用CURL访问URL来每5分执行PHP脚本。Curl默认在标准输出显示输出。使用”curl -o”选项,你也可以把脚本的输出转储到临时文件。 */5 * * * * /usr/bin/curl -o temp.txt http://www.jb51.net/myscript.php下面的例子是使用WGET访问URL来每10分执行PHP脚本。-q选项表示安静模式。”-O temp.txt”表示输出会发送到临时文件。*/10 * * * * /usr/bin/wget -q -O temp.txt http://www.jb51.net/myscript.php 参数:-e 编辑该用户的计时器设置。-l 列出该用户的计时器设置。-r 删除该用户的计时器设置。-u<用户名称> 指定要设定计时器的用户名称。crontab 格式:基本格式 :分钟 小时 日 月 星期 命令第1列表示分钟1~59 每分钟用或者 /1表示第2列表示小时1~23(0表示0点)第3列表示日期1~31第4列 表示月份1~12第5列标识号星期0~6(0表示星期天)第6列要运行的命令记住几个特殊符号的含义: “*”代表取值范围内的数字, “/”代表”每”, “-”代表从某个数字到某个数字, “,”分开几个离散的数字 crontab文件的一些例子:30 21 * * * /usr/local/etc/rc.d/lighttpd restart 上面的例子表示每晚的21:30重启apache。 45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart 上面的例子表示每月1、10、22日的4 : 45重启apache。 10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart 上面的例子表示每周六、周日的1 : 10重启apache。 0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart 上面的例子表示在每天18 : 00至23 : 00之间每隔30分钟重启apache。 0 23 * * 6 /usr/local/etc/rc.d/lighttpd restart 上面的例子表示每星期六的11 : 00 pm重启apache。 0 */1 * * * /usr/local/etc/rc.d/lighttpd restart 每一小时重启apache 0 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart 晚上11点到早上7点之间,每隔一小时重启apache 0 11 4 * mon-wed /usr/local/etc/rc.d/lighttpd restart 每月的4号与每周一到周三的11点重启apache 0 4 1 jan * /usr/local/etc/rc.d/lighttpd restart
2022年07月14日
206 阅读
0 评论
0 点赞
2022-07-02
【composer】composer常用命令
全局配置(推荐) 所有项目都会使用该镜像地址:composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/取消配置:composer config -g --unset repos.packagist若项目之前已通过其他源安装,则需要更新 composer.lock 文件,执行命令:composer update --lock1、composer list:获取帮助信息; 2、composer init:以交互方式填写composer.json文件信息; 3、composer install:从当前目录读取composer.json文件,处理依赖关系,并安装到vendor目录下; 4、composer update:获取依赖的最新版本,升级composer.lock文件; 5、composer require:添加新的依赖包到composer.json文件中并执行更新; composer remove twbs/bootstrap; 卸载依赖包 6、composer search:在当前项目中搜索依赖包; 7、composer show:列举所有可用的资源包; 8、composer validate:检测composer.json文件是否有效; 9、composer self-update:将composer工具更新到最新版本; composer self-update -r :回滚到安装的上一个版本 10、composer diagnose:执行诊断命令 11、composer clear:清除缓存 10、composer create-project:基于composer创建一个新的项目; 11、composer dump-autoload:在添加新的类和目录映射是更新autoloader 关于composer遇到的问题1.You may need to run composer update with the “–no-plugins” option.回滚到安装的上一个版本Failed to decode response: zlib_decode(): data error 更新失败提示:更换回原来的源2.composer config -g repo.packagist composer https://packagist.phpcomposer.com更新组件提示:升级自身版本composer self-update
2022年07月02日
787 阅读
2 评论
0 点赞
2022-06-29
【JavaScript】js接受后端变量处理数组 eval()
前端 var arr = eval("{$arr}"); 后端: $arr = json_encode($dtArr); 'arr' => str_replace('"','',$arr),
2022年06月29日
210 阅读
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 点赞
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日
251 阅读
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日
200 阅读
0 评论
0 点赞
2022-06-25
【Linux】开启关闭防火墙
CentOS 5/CentOS 6在CentOS 5和CentOS 6系统中,关于如何开启防火墙、关闭防火墙、查看防火墙运行状态,请参考以下信息:开启防火墙 service iptables start 关闭防火墙 service iptables stop 查看防火墙运行状态 service iptables statusCentOS 7/Red Hat 7/Alibaba Cloud Linux 2在CentOS 7、Red Hat和Alibaba Cloud Linux 2系统中,关于如何开启防火墙、关闭防火墙、查看防火墙运行状态,请参考以下信息:开启防火墙 systemctl start firewalld.service关闭防火墙 systemctl stop firewalld.service查看防火墙运行状态 firewall-cmd --stateUbuntu在Ubuntu系统中,关于如何开启防火墙、关闭防火墙、查看防火墙运行状态,请参考以下信息:开启防火墙 ufw enable关闭防火墙 ufw disable查看防火墙运行状态 ufw statusDebian在Debian系统中,默认没有安装防火墙,可以通过清空防火墙策略,删除相关屏蔽规则。具体操作如下所示:注意:清空策略前,请务必备份防火墙策略。依次执行以下命令,备份防火墙策略。touch [$Iptables] iptables-save > [$Iptables]说明:[$Iptables]为防火墙策略的备份文件地址。执行以下命令,清空防火墙策略。iptables -F
2022年06月25日
264 阅读
0 评论
0 点赞
2022-06-23
【composer】composer 常用命令
1、composer安装 ------------ 官方地址:https://getcomposer.org/download/ 下载地址:https://getcomposer.org/Composer-Setup.exe 下载后直接安装即可。 2、检查是否安装完成 ---------- > composer --version > composer -V 注意这里要大写 > composer -vvv 命令查看更详细的信息,及帮助。 composer -V Composer version 2.0.9 2021-01-27 16:09:27 3、composer配置镜像 -------------- 因为composer是国外地址,访问起来特别慢,所以使用的时候很容易出现安装失败的情况,这里的解决办法就是使用镜像,使用composer config命令配置镜像地址即可。这里推荐使用阿里云composer镜像源,优点是快速稳定更新快 **3.1、全局配置(推荐)** 所有项目都会使用该镜像地址: composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ 取消配置: composer config -g --unset repos.packagist **3.2、当前项目配置** 仅修改当前工程配置,仅当前工程可使用该镜像地址: composer config repo.packagist composer https://mirrors.aliyun.com/composer/ 取消配置: composer config --unset repos.packagist 4、composer使用 ------------ **4.1、install命令** > install命令可以用于项目初始化后,初次安装依赖,且会优先读取composer.lock中的版本号,以尽可能的保证协作开发中包版本的一致性。 composer install **4.2、require命令(不编辑composer.json的情况下安装库)** > 你可能会觉得每安装一个库都需要修改composer.json太麻烦,那么你可以直接使用require命令。 require > 命令,添加新的依赖包到composer.json文件中并执行更新。 composer require laravel/ui x.0.0 #下载指定版本,可指定 > 这个方法也可以用来快速地新开一个项目。init命令有–require选项,可以自动编写composer.json:(注意我们使用-n,这样就不用回答问题) $ composer init --require=foo/bar:1.0.0 -n $ cat composer.json { "require": { "foo/bar": "1.0.0" } } **4.3、update命令** > update命令无法在命令行中指定包版本号,需要手动修改composer.json文件 composer update 仅更新单个库 只想更新某个特定的库,不想更新它的所有依赖,很简单: composer update foo/bar **4.4、创建项目** > 初始化的时候,你试过create-project命令么? > 2.2.0 这会自动克隆仓库,并检出指定的版本。克隆库的时候用这个命令很方便,不需要搜寻原始的URI了。 composer create-project doctrine/orm path 2.2.0 **4.5、其他常用命令** composer list:获取帮助信息; composer init:以交互方式填写composer.json文件信息; composer search:在当前项目中搜索依赖包; composer show:列举所有可用的资源包; composer show -t:树状列举所有可用的资源包; composer show laravel/framework:这将向您显示安装的版本、它的许可证和依赖项以及它在本地安装的位置等信息。 composer outdated: 检测一下已安装的包,哪些有可以升级的; composer outdated -m:如果希望高亮显示小的升级版本,可以使用 outdated 命令,以 --minor-only 或者 -m 参数 ; composer why vlucas/phpdotenv:如果您想知道安装特定软件包的原因,可以使用 why 命令来确定哪些依赖项需要它; composer why-not laravel/framework 5.8 -t:有时,一个或多个已安装的软件包将阻止安装或更新软件包。 ; composer validate:检测composer.json文件是否有效; composer create-project:基于composer创建一个新的项目; composer dump-autoload:在添加新的类和目录映射是更新autoloader composer remove laravel/ui :删除依赖后还需要去vender文件夹里,手动删除 composer status -v:您可以使用 --verbose 或 -v 参数来查看本地修改的软件包和文件 composer licenses:用于查询许可的完整列表: 5、奇淫巧技 ------ 5.1、考虑缓存,dist包优先 > 最近一年以来的Composer会自动存档你下载的dist包。默认设置下,dist包用于加了tag的版本, > 例如"symfony/symfony":“v2.1.4”,或者是通配符或版本区间,“2.1.*“或”>=2.2,<2.3-dev”(如果你使用stable作为你的minimum-stability)。 > dist包也可以用于诸如dev-master之类的分支,Github允许你下载某个git引用的压缩包。 > 为了强制使用压缩包,而不是克隆源代码,你可以使用install和update的–prefer-dist选项 下面是一个例子(我使用了–profile选项来显示执行时间): $ composer init --require="twig/twig:1.*" -n --profile Memory usage: 3.94MB (peak: 4.08MB), time: 0s $ composer install --profile Loading composer repositories with package information Installing dependencies - Installing twig/twig (v1.12.2) Downloading: 100% Writing lock file Generating autoload files Memory usage: 10.13MB (peak: 12.65MB), time: 4.71s $ rm -rf vendor $ composer install --profile Loading composer repositories with package information Installing dependencies from lock file - Installing twig/twig (v1.12.2) Loading from cache Generating autoload files Memory usage: 4.96MB (peak: 5.57MB), time: 0.45s 这里,twig/twig:1.12.2的压缩包被保存在~/.composer/cache/files/twig/twig/1.12.2.0-v1.12.2.zip。重新安装包时直接使用。 **5.2、若要修改,源代码优先** > 当你需要修改库的时候,克隆源代码就比下载包方便了。你可以使用–prefer-source来强制选择克隆源代码。 composer update symfony/yaml --prefer-source 接下来你可以修改文件: composer status -v You have changes in the following dependencies: /path/to/app/vendor/symfony/yaml/Symfony/Component/Yaml: M Dumper.php 当你试图更新一个修改过的库的时候,Composer会提醒你,询问是否放弃修改: $ composer update Loading composer repositories with package information Updating dependencies - Updating symfony/symfony v2.2.0 (v2.2.0- => v2.2.0) The package has modified files: M Dumper.php Discard changes [y,n,v,s,?]? **5.3、为生产环境作准备** 最后提醒一下,在部署代码到生产环境的时候,别忘了优化一下自动加载: composer dump-autoload --optimize 安装包的时候可以同样使用–optimize-autoloader。不加这一选项,你可能会发现20%到25%的性能损失。 6、其它 ---- 参考文档:https://docs.phpcomposer.com/03-cli.html 参考链接:https://blog.csdn.net/jugtba/article/details/117379062
2022年06月23日
275 阅读
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日
145 阅读
0 评论
0 点赞
1
2
3
4
...
11