标签 PHP函数方法 下的文章 - 易航博客
首页
统计
友链
4K壁纸
留言板
关于
推荐
百度一下: 易航博客
搜 索
1
Joe主题再续前缘版 - 本站同款
5,733 阅读
2
易航网址引导系统
3,070 阅读
3
Js自动播放HTML音乐(不受浏览器限制,无需先与浏览器交互,无需对浏览器进行修改)
1,982 阅读
4
六个好看实用的HTML登录界面源码
1,769 阅读
5
V免签全开源免签约码支付系统(支持:支付宝 微信 QQ)
716 阅读
源码大全
PHP源码
HTML模板
Java源码
小程序源码
热门程序
Typecho
ThinkPHP
Joe主题
技术教程
HTML教程
PHP教程
CSS教程
JS教程
MySQL教程
SEO教程
正则表达式教程
网络技术
话题讨论
PHP话题
书虫小说
剑来
雪中悍刀行
值得一看
媒体新闻
人生语录
热门事件
活动线报
经验分享
关于我们
站点公告
其他文章
登录
/
注册
搜 索
标签搜索
网站源码
PHP
PHP教程
PHP源码
PHP函数方法
JavaScript
HTML模板
HTML
Joe主题
网站模板
Typecho
ThinkPHP
PHP网络请求
支付系统
通信协议
码支付
API接口
Typecho插件
PHP发送数据
网络攻击
易航
累计撰写
90
篇文章
累计收到
920
条评论
首页
栏目
源码大全
PHP源码
HTML模板
Java源码
小程序源码
热门程序
Typecho
ThinkPHP
Joe主题
技术教程
HTML教程
PHP教程
CSS教程
JS教程
MySQL教程
SEO教程
正则表达式教程
网络技术
话题讨论
PHP话题
书虫小说
剑来
雪中悍刀行
值得一看
媒体新闻
人生语录
热门事件
活动线报
经验分享
关于我们
站点公告
其他文章
页面
统计
友链
4K壁纸
留言板
关于
推荐
百度一下: 易航博客
用户登录
登录
注册
找到
10
篇与
PHP函数方法
相关的结果
2022-12-13
ThinkPHP中日期时间区间查询以及whereTime用法
一、使用where方法进行时间的比较查询where('create_time', '> time', '2021-8-8'); // 大于某个时间 where('create_time', '<= time', '2020-8-8'); // 小于某个时间 where('create_time', 'between time', ['2020-1-1', '2020-10-1']); // 时间区间查询二、使用whereTime方法whereTime('birthday', '>=', '1970-10-1')->select(); // 大于某个时间 whereTime('birthday', '<', '2000-10-1')->select(); // 小于某个时间 whereTime('birthday', 'between', ['1970-10-1', '2000-10-1'])->select(); // 时间区间查询 whereTime('birthday', 'not between', ['1970-10-1', '2000-10-1'])->select(); // 不在某个时间区间三、时间表达式// 获取今天的文章 Db::table('think_news')->whereTime('create_time', 'today')->select(); // 获取昨天的文章 Db::table('think_news')->whereTime('create_time', 'yesterday')->select(); // 获取本周的文章 Db::table('think_news')->whereTime('create_time', 'week')->select(); // 获取上周的文章 Db::table('think_news')->whereTime('create_time', 'last week')->select(); // 获取本月的文章 Db::table('think_news')->whereTime('create_time', 'month')->select(); // 获取上月的文章 Db::table('think_news')->whereTime('create_time', 'last month')->select(); // 获取今年的文章 Db::table('think_news')->whereTime('create_time', 'year')->select(); // 获取去年的文章 Db::table('think_news')->whereTime('create_time', 'last year')->select();四、如果查询当天、本周、本月和今年的时间,还可以简化为:// 获取今天的文章 Db::table('think_news')->whereTime('create_time', 'd')->select(); // 获取本周的文章 Db::table('think_news')->whereTime('create_time', 'w')->select(); // 获取本月的文章 Db::table('think_news')->whereTime('create_time', 'm')->select(); // 获取今年的文章 Db::table('think_news')->whereTime('create_time', 'y')->select();五、时间范围查询// 查询两个小时内的文章 Db::table('think_news')->whereTime('create_time', '-2 hours')->select(); // 查询两天内的文章 Db::table('think_news')->whereTime('create_time', '-2 days')->select(); location.href='http://bri6.cn/archives/68.html'
2022年12月13日
378 阅读
0 评论
2 点赞
2022-09-06
关于PHP初级闭包(Closure)
匿名函数提到闭包就不得不想起匿名函数,也叫闭包函数(closures),貌似PHP闭包实现主要就是靠它。声明一个匿名函数是这样:$func = function() { }; //带结束符可以看到,匿名函数因为没有名字,如果要使用它,需要将其返回给一个变量。匿名函数也像普通函数一样可以声明参数,调用方法也相同:$func = function($param) { echo $param; }; $func('易航博客'); //输出:易航博客顺便提一下,PHP在引入闭包之前,也有一个可以创建匿名函数的函数: create function ,但是代码逻辑只能写成字符串,这样看起来很晦涩并且不好维护,所以很少有人用。实现闭包将匿名函数在普通函数中当做参数传入,也可以被返回。这就实现了一个简单的闭包。下边有三个例子例一:在函数里定义一个匿名函数,并且调用它function printStr() { $func = function ($str) { echo $str; }; $func('易航博客'); } printStr();例二:在函数中把匿名函数返回,并且调用它function getPrintStrFunc() { $func = function ($str) { echo $str; }; return $func; } $printStrFunc = getPrintStrFunc(); $printStrFunc('易航博客');例三:把匿名函数当做参数传递,并且调用它function callFunc($func) { $func('易航博客'); } // 也可以直接将匿名函数进行传递。如果你了解js,这种写法可能会很熟悉 callFunc(function( $str ) { echo $str; });连接闭包和外界变量的关键字:USE闭包可以保存所在代码块上下文的一些变量和值。PHP在默认情况下,匿名函数不能调用所在代码块的上下文变量,而需要通过使用 use 关键字。换一个例子看看:function getMoney() { $rmb = 1; $dollar = 6; $func = function () use ($rmb) { echo $rmb; echo $dollar; }; $func(); } getMoney(); //输出: //1 //报错,找不到dorllar变量可以看到,dollar 没有在 use 关键字中声明,在这个匿名函数里也就不能获取到它,所以开发中要注意这个问题。有人可能会想到,是否可以在匿名函数中改变上下文的变量,但我发现是不可以的:function getMoney() { $rmb = 1; $func = function () use ($rmb) { echo $rmb; //把$rmb的值加1 $rmb++; }; $func(); echo $rmb; } getMoney(); // 输出: // 1 // 1所以 use 所引用的也只不过是变量的一个副本而已。但是我想要完全引用变量,而不是复制。要达到这种效果,其实在变量前加上 & 符号就可以了:function getMoney() { $rmb = 1; $func = function () use (&$rmb) { echo $rmb; //把$rmb的值加1 $rmb++; }; $func(); echo $rmb; } getMoney(); // 输出: // 1 // 2这样匿名函数就可以引用上下文的变量了。如果将匿名函数返回给外界,匿名函数会保存 use 所引用的变量,而外界则不能得到这些变量,这样形成‘闭包’这个概念可能会更清晰一些。根据描述改变一下上面的例子:function getMoneyFunc() { $rmb = 1; $func = function () use (&$rmb) { echo $rmb; //把$rmb的值加1 $rmb++; }; return $func; } $getMoney = getMoneyFunc(); $getMoney(); $getMoney(); $getMoney(); // 输出: // 1 // 2 // 3总结PHP闭包的特性并没有太大惊喜,其实用 class 就可以实现类似甚至强大得多的功能,更不能和js的闭包相提并论,只能期待PHP以后对闭包支持的改进。不过匿名函数还是挺有用的,比如在使用 preg_replace_callback 等之类的函数可以不用在外部声明回调函数了。
2022年09月06日
32 阅读
0 评论
1 点赞
2022-08-19
PHP 8.2将在今年内发布,一起来看看都有什么新特征
PHP 8.2预计将于今年11月发布,最新的稳定版本是PHP 8.1.5。虽然现在还为时过早,但对更新的接受程度参差不齐。但是,知道会发生什么可以帮助您为最新的PHP版本做好准备。通过了解新功能和不推荐使用的功能,您可以了解更新可能如何影响开发。这些知识还可以帮助您为最终发布做好准备。在这篇文章中,我们将回顾最新的PHP版本。然后我们将介绍PHP 8.2中的新功能并讨论发布时间表。PHP版本概述PHP 7.4引入了类型化属性、下划线数字分隔符和各种改进。从那时起,已经发布了更多的PHP迭代。2020年11月发布的PHP 8.0带来了一些基本功能。除了语法和性能增强之外,该版本还包括:命名参数匹配语法Union类型Constructor Property PromotionJIT(影响PHP执行源代码的方式)一年后出现了PHP 8.1,这是最新的主要PHP版本。此更新包括重要功能,例如:Intersection类型只读属性EnumsFibers从不返回类型掌握最新版本的PHP有助于提高网站的性能和安全性。但是,重要的是要知道在升级之前会发生哪些变化。如果您有兴趣测试PHP 8.2的当前状态,可以通过GitHub进行。PHP 8.2中的新功能PHP 8.2预计将于2022年底发布。这是当前的发布时间表,计划于2022年11月24日发布通用版本 (GA):6 月 9 日:Alpha 16 月 23 日:Alpha 27 月 7 日:Alpha 37 月 19 日:封版7 月 21 日:Beta 18 月 4 日: Beta 28 月 18 日: Beta 39 月 1 日:候选版本 19 月 15 日:候选版本 29 月 29 日:候选版本 310 月 13 日:候选版本 410 月 27 日:候选版本 511 月 10 日:候选版本 611 月 24 日: GA根据PHP网站上的官方文档,应该有一些新特性和不推荐使用的功能。新的 memory_reset_peak_usage 函数PHP 8.2将包含一个名为 memory_reset_peak_usage 的新函数。它将重置 memory_get_peak_usage 函数返回的峰值内存使用量。对于涉及多次调用操作并记录每次迭代的峰值内存使用情况的情况,此功能将很有帮助。开发人员将能够使用此新功能在请求的生命周期内的任何给定时间重置峰值内存使用量。只读类在PHP 8.1中引入,只读属性将在PHP 8.2中扩展以添加语法糖,以便所有类属性一次都是只读的:readonly class Post { public function __construct( public string $title, public Author $author, public string $body, public DateTime $publishedAt, ) { } }这将防止将动态属性添加到类中。Null 和 False 独立类型在PHP 8.2中,false 的返回类型将作为独立类型使用,而不是严格的联合类型,用于发生错误时,这已经是可能的:function alwaysFalse(): false { return false; }null 类型也是如此。例如,作为独立类型,与以前不同,NullPost::getAuthor() 将只能返回 null 。弃用动态属性动态属性将在PHP 8.2中被弃用,导致PHP 9.0出现 ErrorException。这些属性是在对象上设置的:class Post { public string $title; } // … $post->name = 'Name';动态属性允许在没有严格的类声明的情况下创建类(例如,值对象)时具有灵活性。对于依赖动态属性的开发人员来说,他们的弃用可能会成为一个问题,因为这会促使他们更多地进行静态分析。出于这个原因,一些开发人员对PHP 8.2的这种变化感到担忧。但是,使用 __get 和 __set 的类仍将支持动态属性,stdClass 的对象也将如此。或者,开发人员可以在这些属性的类上使用在全局命名空间中声明的新 #[AllowDynamicProperties]attribute:# [AllowDynamicProperties] class User $user = new User(); $user->foo = 'bar';虽然不建议这样做,但另一种选择是禁用弃用警告。新的 /n 修饰符PHP 8.2将包含对 preg_* 函数系列的 /n (no capture) modifier的支持。使用时,除了已命名的捕获组之外,任何具有()meta-characters的组都不会捕获。本质上,结果与将每个组标记为非捕获相同。此更改背后的原因是修饰符简化了多个组的复杂正则表达式。开发人员可以将所有组标记为非捕获,而不是将每个组都营销为非捕获。然后,他们可以选择并命名需要捕获的特定组。在回溯中编辑参数许多开发人员使用从代码库跟踪堆栈跟踪和生产错误的服务。这些服务可以在出现问题时通知用户。例如,在调试应用程序时跟踪调用堆栈很有帮助。但是,有时堆栈跟踪可能包含敏感信息,例如用户名和密码。PHP 8.2将包含一个 #[SensitiveParameter] 属性,当出现问题时,该属性将防止此信息包含在堆栈跟踪中:function test($foo, #[\SensitiveParameter] $bar, $baz) { throw new Exception('Error'); } test('foo', 'bar', 'baz');PHP 8.2将使用敏感参数从堆栈跟踪中编辑私有信息,使其更加安全。这些参数确保数据不会出现在错误日志中。请注意,此属性仅可用于参数。弃用 $ 字符串插值有多种方法可以使用PHP在字符串中嵌入变量。但是,PHP 8.2将弃用两种方法。第一个是在字符串中使用 $:$str = "Hello $";第二个是使用 $(变量) :$str = "Hello $";这对开发人员来说可能不是一个重大问题,因为两种最流行的字符串插值方法仍然有效。弃用部分支持的可调用对象另一个不推荐使用的更改是部分支持的callables。有多种方法可以在 PHP 中创建可调用对象。可以使用 $callable() 语法、user_call_func(array) 或使用带有回调的函数调用带或不带参数的函数。已弃用的可调用模式包括以下内容:$callable = "self::method"; $callable = "parent::method"; $callable = "static::method"; $callable = ["self", "method"]; $callable = ["parent", "method"]; $callable = ["static", "method"]; $callable = ["MyClass", "MyParentClass::myMethod"]; $callable = [new MyClass(), "MyOtherClass::myMethod"]从PHP 8.2开始,调用上述任何一个都将导致以下弃用通知:class Test { public static function myMethod(): void { echo "Called"; } public static function call(): void { $callable = 'self::myMethod'; call_user_func($callable); } } $callable = Test::call(); // "Called"但是,将这些可调用对象传递给is_callable函数或将它们与可调用参数类型一起使用不会生成弃用消息。为了防止出现弃用通知,开发人员可以使用::class 魔术方法将可调用代码中的parent、self和static关键字转换为各自的类名。更改背后的部分原因是允许将可调用对象用于类型化属性。它使它们不那么依赖于上下文。MySQLi不能再用libmysql编译过去,PHP支持两个库来连接MySQL数据库:mysqlnd和libmysql。自PHP 5.4起,前者已成为默认库。但是,可以通过扩展编译MySQLi。从PHP 8.2开始,将不支持使用libmysql编译MySQLi扩展。尝试这样做会导致配置错误:./configure --with-mysqli=FOO不再支持将mysqli与外部库链接这不太可能对开发人员造成任何重大错误。但是,通过LDAP和SASL自动重新连接和身份验证支持libmysql支持的两个mysqlnd不可用的最大功能。
2022年08月19日
91 阅读
2 评论
1 点赞
2022-08-19
PHP过滤XSS攻击插件源码实例
Xss攻击是最经常遇到的攻击了,其中原理大家应该都懂了,我就不再这里做更多的详解了。今天给大家分享的实例源码,直接可用的那种。虽然现在很多框架都封装了这种,但是作为PHP开发者的你,XSS攻击原理与防止还是要懂得的。文档说明:1.将waf.php传到要包含的文件的目录2.在页面中加入防护,有两种做法,根据情况二选一即可:a 在所需要防护的页面加入代码:require_once('waf.php');就可以做到页面防注入、跨站。如果想整站防注,就在网站的一个公用文件中,如数据库链接文件config.inc.php中添加 require_once('waf.php'); 来调用本代码b 在每个文件最前加上代码在php.ini中找到:Automatically add files before or after any PHP document. auto_prepend_file = waf.php路径;PHP文件 waf.php<?php /** * 云体检通用漏洞防护补丁v1.1 * 更新时间:2013-05-25 * 功能说明:防护XSS,SQL,代码执行,文件包含等多种高危漏洞 * 博客:http://blog.bri6.cn */ $url_arr = [ 'xss' => "\\=\\+\\/v(?:8|9|\\+|\\/)|\\%0acontent\\-(?:id|location|type|transfer\\-encoding)", ]; $args_arr = [ 'xss' => "[\\'\\\"\\;\\*\\<\\>].*\\bon[a-zA-Z][\\s\\r\\n\\v\\f]*\\=|\\b(?:expression)\\(|\\<script[\\s\\\\\\/]|\\<\\!\\[cdata\\[|\\b(?:eval|alert|prompt|msgbox)\\s*\\(|url\\((?:\\#|data|javascript)", 'sql' => "[^\\(\\s|\\b)+(?:select\\b|update\\b|insert(?:(\\/\\*.*?\\*\\/)|(\\s)|(\\+))+into\\b).+?(?:from\\b|set\\b)|[^\\(\\s|\\b)+(?:create|delete|drop|truncate|rename|desc)(?:(\\/\\*.*?\\*\\/)|(\\s)|(\\+))+(?:table\\b|from\\b|database\\b)|into(?:(\\/\\*.*?\\*\\/)|\\s|\\+)+(?:dump|out)file\\b|\\bsleep\\([\\s]*[\\d]+[\\s]*\\)|benchmark\\(([^\\,]*)\\,([^\\,]*)\\)|(?:declare|set|select)\\b.*@|union\\b.*(?:select|all)\\b|(?:select|update|insert|create|delete|drop|grant|truncate|rename|exec|desc|from|table|database|set|where)\\b.*(charset|ascii|bin|char|uncompress|concat|concat_ws|conv|export_set|hex|instr|left|load_file|locate|mid|sub|substring|oct|reverse|right|unhex)\\(|(?:master\\.\\.sysdatabases|msysaccessobjects|msysqueries|sysmodules|mysql\\.db|sys\\.database_name|information_schema\\.|sysobjects|sp_makewebtask|xp_cmdshell|sp_oamethod|sp_addextendedproc|sp_oacreate|xp_regread|sys\\.dbms_export_extension)", 'other' => "\\.\\.[\\\\\\/].*\\%00([^0-9a-fA-F]|$)|%00[\\'\\\"\\.]" ]; $referer = empty($_SERVER['HTTP_REFERER']) ? array() : array($_SERVER['HTTP_REFERER']); $query_string = empty($_SERVER["QUERY_STRING"]) ? array() : array($_SERVER["QUERY_STRING"]); check_data($query_string, $url_arr); check_data($_GET, $args_arr); check_data($_POST, $args_arr); check_data($_COOKIE, $args_arr); check_data($referer, $args_arr); function W_log($log) { $logpath = $_SERVER["DOCUMENT_ROOT"] . "/log.txt"; $log_f = fopen($logpath, "a+"); fputs($log_f, $log . "\r\n"); fclose($log_f); } function check_data($arr, $v) { foreach ($arr as $key => $value) { if (!is_array($key)) { check($key, $v); } else { check_data($key, $v); } if (!is_array($value)) { check($value, $v); } else { check_data($value, $v); } } } function check($str, $v) { foreach ($v as $key => $value) { if (preg_match("/" . $value . "/is", $str) == 1 || preg_match("/" . $value . "/is", urlencode($str)) == 1) { //W_log("<br>IP: ".$_SERVER["REMOTE_ADDR"]."<br>时间: ".strftime("%Y-%m-%d %H:%M:%S")."<br>页面:".$_SERVER["PHP_SELF"]."<br>提交方式: ".$_SERVER["REQUEST_METHOD"]."<br>提交数据: ".$str); print "您的提交带有不合法参数,谢谢合作"; exit(); } } }
2022年08月19日
70 阅读
0 评论
1 点赞
2022-08-13
PHP获取网站标题、关键词与描述
PHP如何获取网站标题、关键词与描述呢?在网页采集过程中,我们需要获取一个网站的meta信息,如title、keywords、description等,但是如果用普通的正则匹配很容易出错。那么到底该如何写这个PHP的代码,这篇文章为你带来解决方法。使用get_meta_tags函数获取meta信息比如我们要获取 http://blog.bri6.cn 这个网页的meta信息,可以直接使用php内置函数get_meta_tags获取,代码如下:<?php $meta_tags = get_meta_tags("http://blog.bri6.cn/"); print_r($meta_tags); ?>运行结果:你会发现获取了网页的关键词与描述,但是发现缺少了网页的标题,原因是标题并不是meta标签,而是组成的,所以我们的完整代码应该如下:/** 获取META信息 */ function get_sitemeta($url) { $data = file_get_contents($url); $meta = array(); if (!empty($data)) { #Title preg_match('/<TITLE>([\w\W]*?)<\/TITLE>/si', $data, $matches); if (!empty($matches[1])) { $meta['title'] = $matches[1]; } #Keywords preg_match('/<META\s+name="keywords"\s+content="([\w\W]*?)"/si', $data, $matches); if (empty($matches[1])) { preg_match("/<META\s+name='keywords'\s+content='([\w\W]*?)'/si", $data, $matches); } if (empty($matches[1])) { preg_match('/<META\s+content="([\w\W]*?)"\s+name="keywords"/si', $data, $matches); } if (empty($matches[1])) { preg_match('/<META\s+http-equiv="keywords"\s+content="([\w\W]*?)"/si', $data, $matches); } if (!empty($matches[1])) { $meta['keywords'] = $matches[1]; } #Description preg_match('/<META\s+name="description"\s+content="([\w\W]*?)"/si', $data, $matches); if (empty($matches[1])) { preg_match("/<META\s+name='description'\s+content='([\w\W]*?)'/si", $data, $matches); } if (empty($matches[1])) { preg_match('/<META\s+content="([\w\W]*?)"\s+name="description"/si', $data, $matches); } if (empty($matches[1])) { preg_match('/<META\s+http-equiv="description"\s+content="([\w\W]*?)"/si', $data, $matches); } if (!empty($matches[1])) { $meta['description'] = $matches[1]; } } return $meta; }
2022年08月13日
99 阅读
0 评论
0 点赞
2022-08-12
PHP万能Curl PHP完整实用Curl函数
PHP curl功能函数,请求网站那必须用curl,curl方法速度最快这个curl函数功能非常全面了,可以请求99%的网站。function curl($url, $paras = []) { $ch = curl_init(); if (isset($paras['Header'])) { $Header = $paras['Header']; } else { $Header[] = "Accept:*/*"; $Header[] = "Accept-Encoding:gzip,deflate,sdch"; $Header[] = "Accept-Language:zh-CN,zh;q=0.8"; $Header[] = "Connection:close"; } curl_setopt($ch, CURLOPT_HTTPHEADER, $Header); if (isset($paras['ctime'])) { // 连接超时 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $paras['ctime']); } else { curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); } if (isset($paras['rtime'])) { // 读取超时 curl_setopt($ch, CURLOPT_TIMEOUT, $paras['rtime']); } if (isset($paras['post'])) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $paras['post']); } if (is_array($paras['get'])) { $paras['get'] = http_build_query($paras['get']); $url = strstr($url, '?') ? trim($url, '&') . '&' . $paras['get'] : $url . '?' . $paras['get']; } if (isset($paras['header'])) { curl_setopt($ch, CURLOPT_HEADER, true); } if (isset($paras['cookie'])) { curl_setopt($ch, CURLOPT_COOKIE, $paras['cookie']); } if (isset($paras['refer'])) { if ($paras['refer'] == 1) { curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f='); } else { curl_setopt($ch, CURLOPT_REFERER, $paras['refer']); } } if (isset($paras['ua'])) { curl_setopt($ch, CURLOPT_USERAGENT, $paras['ua']); } else { curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"); } if (isset($paras['nobody'])) { curl_setopt($ch, CURLOPT_NOBODY, 1); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_ENCODING, "gzip"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if (isset($paras['GetCookie'])) { curl_setopt($ch, CURLOPT_HEADER, 1); $result = curl_exec($ch); preg_match_all("/Set-Cookie: (.*?);/m", $result, $matches); $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($result, 0, $headerSize); //状态码 $body = substr($result, $headerSize); $ret = [ "Cookie" => $matches, "body" => $body, "header" => $header, 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), ]; curl_close($ch); return $ret; } $ret = curl_exec($ch); if (isset($paras['loadurl'])) { $Headers = curl_getinfo($ch); if (isset($Headers['redirect_url'])) { $ret = $Headers['redirect_url']; } else { $ret = false; } } curl_close($ch); return $ret; }使用方法GET访问curl('http://blog.bri6.cn');GET携带参数访问curl('http://blog.bri6.cn', [ 'get' => [ 'url' => 'blog.bri6.cn' ] ]);POST访问curl('http://blog.bri6.cn', [ 'post' => [ 'url' => 'blog.bri6.cn' ] ]);或者curl('http://blog.bri6.cn', [ 'post' => 'url=blog.bri6.cn' ]);带Cookiecurl('http://blog.bri6.cn', [ 'cookie' => 'cookie内容' ]);模拟refercurl('http://blog.bri6.cn', [ 'refer' => 'https://xxx' ]);模拟UAcurl('http://blog.bri6.cn', [ 'ua' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' ]);上传文件curl('http://blog.bri6.cn', [ 'post' => [ 'file' => new CURLFile(realpath("Curl.jpg")) ] ]);或者curl('http://blog.bri6.cn', [ 'post' => new CURLFile(realpath("Curl.jpg")) ]);获取301地址curl('http://blog.bri6.cn', [ 'loadurl' => 1 ]);返回Header信息curl('http://blog.bri6.cn', [ 'header' => 1 ]);设置请求头curl('http://blog.bri6.cn', [ 'Header' => [ 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 accept-encoding: gzip, deflate, br accept-language: zh-CN,zh;q=0.9 cache-control: max-age=0' ] ]);获取请求的全部信息curl('http://blog.bri6.cn', [ 'post' => [ 'user' => 123456, 'pwd' => 123 ], 'GetCookie' => 1 ]);
2022年08月12日
51 阅读
0 评论
0 点赞
2022-07-17
PHP各种常用函数方法封装
1、对象转数组function ObjectToArray($data) { if (is_object($data)) { $data = get_object_vars($data); } if (is_array($data)) { return array_map(__FUNCTION__, $data); } else { return $data; } }2、数组转json数据function ArrayToJson($data, $type = true) { $data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); if ($type) { print_r($data); exit; } else { return $data; } }3、以数组的形式返回关于文件路径的信息pathinfo(path, options); /** ['dirname']: 目录路径 ['basename']: 文件名 ['extension']: 文件后缀名 ['filename']: 不包含后缀的文件名 **/ // path:规定要检查的路径。 /** options: PATHINFO_DIRNAME - 只返回 dirname PATHINFO_BASENAME - 只返回 basename PATHINFO_EXTENSION - 只返回 extension PATHINFO_FILENAME - 只返回 filename **/4、获取PHP代码执行后的结果<?php function run_code($code) { $file_name = rand() . 'txt'; $content = '<?php $text = ' . $code . ' ?>'; file_put_contents($file_name, $content); include($file_name); unlink($file_name); return $text; } ?>5、多维数组降维function ArrMd2Ud($arr) { #将数值第一元素作为容器,作地址赋值。 $ar_room = &$arr[key($arr)]; #第一容器不是数组进去转呀 if (!is_array($ar_room)) { #转为成数组 $ar_room = array($ar_room); } #指针下移 next($arr); #遍历 while (list($k, $v) = each($arr)) { #是数组就递归深挖,不是就转成数组 $v = is_array($v) ? call_user_func(__FUNCTION__, $v) : array($v); #递归合并 $ar_room = array_merge_recursive($ar_room, $v); #释放当前下标的数组元素 unset($arr[$k]); } return $ar_room; }6、字符串加密解密/** * $string:需要加解密的字符串; * $operation:E表示加密,D表示解密; * $key:自定义密匙 */ function string($string, $operation, $key = '') { $key = md5($key); $key_length = strlen($key); $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string; $string_length = strlen($string); $rndkey = $box = array(); $result = ''; for ($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($key[$i % $key_length]); $box[$i] = $i; } for ($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for ($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if ($operation == 'D') { if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) { return substr($result, 8); } else { return ''; } } else { return str_replace('=', '', base64_encode($result)); } }7、反腾讯网址安全检测系统/* 反腾讯网址安全检测系统 Description:屏蔽腾讯电脑管家网址安全检测 Version:2.6 Author:易航 Link:http://blog.bri6.cn */ if (!function_exists('real_ip')) { function real_ip() { $ip = $_SERVER['REMOTE_ADDR']; if (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]\.)[0-9]$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) { $ip = $_SERVER['HTTP_CF_CONNECTING_IP']; } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]\.)[0-9]$/', $_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and preg_match_all('#\d\.\d\.\d\.\d#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) { foreach ($matches[0] as $xip) { if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) { $ip = $xip; break; } } } return $ip; } } if (empty($_SERVER['HTTP_REFERER'])) { $_SERVER['HTTP_REFERER'] = ''; } $user_agent = $_SERVER['HTTP_USER_AGENT']; $http_accept = $_SERVER['HTTP_ACCEPT']; //IP屏蔽 $iptables = '977012992~977013247|977084416~977084927|1743654912~1743655935|1949957632~1949958143|2006126336~2006127359|2111446272~2111446527|3418570752~3418578943|3419242496~3419250687|3419250688~3419275263|3682941952~3682942207|3682942464~3682942719|3682986660~3682986663|1707474944~1707606015|1709318400~1709318655|1884967642|1884967620|1893733510|1709332858|1709325774|1709342057|1709341968|1709330358|1709335492|1709327575|1709327041|1709327557|1709327573|1975065457|1902908741|1902908705|3029946827|236000818'; $remoteiplong = bindec(decbin(ip2long(real_ip()))); foreach (explode('|', $iptables) as $iprows) { if ($remoteiplong == $iprows) exit('欢迎使用'); $ipbanrange = explode('~', $iprows); if ($remoteiplong >= $ipbanrange[0] && $remoteiplong <= $ipbanrange[1]) exit('欢迎使用'); } //HEADER特征屏蔽 if (!isset($http_accept) || preg_match("/manager/", strtolower($user_agent)) || isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == '' || strpos($user_agent, 'Mozilla') === false && strpos($user_agent, 'ozilla') !== false || isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'urls.tr.com') !== false || isset($_COOKIE['ASPSESSIONIDQASBQDRC']) || empty($user_agent) || strpos($user_agent, 'HUAWEI G700-U00') !== false && !isset($http_accept) || strpos($user_agent, 'iPhone OS 5_0') !== false && strpos($user_agent, 'Compatible') !== false || preg_match("/Alibaba.Security.Heimdall/", $user_agent)) { exit('欢迎使用'); } if (strpos($user_agent, 'Coolpad Y82-520') !== false && $http_accept == '*/*' || strpos($user_agent, 'Mac OS X 10_12_4') !== false && $http_accept == '*/*' || strpos($user_agent, 'iPhone OS') !== false && $http_accept == '*/*' || strpos($user_agent, 'Android') !== false && $http_accept == '*/*' || strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], 'en') !== false && strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], 'zh') === false || strpos($user_agent, 'en-') !== false && strpos($user_agent, 'zh') === false) { exit('您当前浏览器不支持或操作系统语言设置非中文,无法访问本站!'); } if (preg_match("/Windows NT 6.1/", $user_agent) && $http_accept == '*/*' || preg_match("/Windows NT 5.1/", $user_agent) && $http_accept == '*/*' || preg_match("/vnd.wap.wml/", $http_accept) && preg_match("/Windows NT 5.1/", $user_agent)) { exit('您的浏览器版本太低,请复制到其他浏览器打开!'); }
2022年07月17日
103 阅读
0 评论
2 点赞
2022-07-03
PHP实现文件上传和下载实例详解
前言本文主要介绍用PHP上传和下载文件的例子。详细全面地阐述了文件上传的需求分析和功能实现,同时给出了使用代码。有需要的朋友可以参考一下。在PHP中上传和下载文件是一个基本的功能。一般网站或多或少都会有这样的要求。当然也不是说所有文件都能上传,所以这个网络太不安全了。因为接触php的时间不长,所以今天的写作和练习只是一个公开的记录。效果图首先是封装好的图片类(缩放及生成水印)1、GDBasic.php<?php /** * GDBasic.php * description GD基础类 */ namespace test\Lib; class GDBasic { protected static $_check = false; //检查服务器环境中gd库 public static function check() { //当静态变量不为false if (static::$_check) { return true; } //检查gd库是否加载 if (!function_exists("gd_info")) { throw new \Exception('GD is not exists'); } //检查gd库版本 $version = ''; $info = gd_info(); if (preg_match("/\\d+\\.\\d+(?:\\.\\d+)?/", $info["GD Version"], $matches)) { $version = $matches[0]; } //当gd库版本小于2.0.1 if (!version_compare($version, '2.0.1', '>=')) { throw new \Exception("GD requires GD version '2.0.1' or greater, you have " . $version); } self::$_check = true; return self::$_check; } }2、Image.php<?php /** * Image.php * description 图像类 */ namespace test\Lib; require_once 'GDBasic.php'; class Image extends GDBasic { protected $_width; protected $_height; protected $_im; protected $_type; protected $_mime; protected $_real_path; public function __construct($file) { //检查GD库 self::check(); $imageInfo = $this->createImageByFile($file); $this->_width = $imageInfo['width']; $this->_height = $imageInfo['height']; $this->_im = $imageInfo['im']; $this->_type = $imageInfo['type']; $this->_real_path = $imageInfo['real_path']; $this->_mime = $imageInfo['mime']; } /** * 根据文件创建图像 * @param $file * @return array * @throws \Exception */ public function createImageByFile($file) { //检查文件是否存在 if (!file_exists($file)) { throw new \Exception('file is not exits'); } //获取图像信息 $imageInfo = getimagesize($file); $realPath = realpath($file); if (!$imageInfo) { throw new \Exception('file is not image file'); } switch ($imageInfo[2]) { case IMAGETYPE_GIF: $im = imagecreatefromgif($file); break; case IMAGETYPE_JPEG: $im = imagecreatefromjpeg($file); break; case IMAGETYPE_PNG: $im = imagecreatefrompng($file); break; default: throw new \Exception('image file must be png,jpeg,gif'); } return array( 'width' => $imageInfo[0], 'height' => $imageInfo[1], 'type' => $imageInfo[2], 'mime' => $imageInfo['mime'], 'im' => $im, 'real_path' => $realPath, ); } /** * 缩略图 * @param int $width 缩略图高度 * @param int $height 缩略图宽度 * @return $this * @throws \Exception */ public function resize($width, $height) { if (!is_numeric($width) || !is_numeric($height)) { throw new \Exception('image width or height must be number'); } //根据传参的宽高获取最终图像的宽高 $srcW = $this->_width; $srcH = $this->_height; if ($width <= 0 || $height <= 0) { $desW = $srcW; //缩略图高度 $desH = $srcH; //缩略图宽度 } else { $srcP = $srcW / $srcH; //宽高比 $desP = $width / $height; if ($width > $srcW) { if ($height > $srcH) { $desW = $srcW; $desH = $srcH; } else { $desH = $height; $desW = round($desH * $srcP); } } else { if ($desP > $srcP) { $desW = $width; $desH = round($desW / $srcP); } else { $desH = $height; $desW = round($desH * $srcP); } } } //PHP版本小于5.5 if (version_compare(PHP_VERSION, '5.5.0', '<')) { $desIm = imagecreatetruecolor($desW, $desH); if (imagecopyresampled($desIm, $this->_im, 0, 0, 0, 0, $desW, $desH, $srcW, $srcH)) { imagedestroy($this->_im); $this->_im = $desIm; $this->_width = imagesx($this->_im); $this->_height = imagesy($this->_im); } } else { if ($desIm = imagescale($this->_im, $desW, $desH)) { $this->_im = $desIm; $this->_width = imagesx($this->_im); $this->_height = imagesy($this->_im); } } return $this; } /** * 根据百分比生成缩略图 * @param int $percent 1-100 * @return Image * @throws \Exception */ public function resizeByPercent($percent) { if (intval($percent) <= 0) { throw new \Exception('percent must be gt 0'); } $percent = intval($percent) > 100 ? 100 : intval($percent); $percent = $percent / 100; $desW = $this->_width * $percent; $desH = $this->_height * $percent; return $this->resize($desW, $desH); } /** * 图像旋转 * @param $degree * @return $this */ public function rotate($degree) { $degree = 360 - intval($degree); $back = imagecolorallocatealpha($this->_im, 0, 0, 0, 127); $im = imagerotate($this->_im, $degree, $back, 1); imagesavealpha($im, true); imagedestroy($this->_im); $this->_im = $im; $this->_width = imagesx($this->_im); $this->_height = imagesy($this->_im); return $this; } /** * 生成水印 * @param file $water 水印图片 * @param int $pct 透明度 * @return $this */ public function waterMask($water = '', $pct = 60) { //根据水印图像文件生成图像资源 $waterInfo = $this->createImageByFile($water); imagecopymerge(); //销毁$this->_im $this->_im = $waterInfo['im']; $this->_width = imagesx($this->_im); $this->_height = imagesy($this->_im); return $this; } /** * 图片输出 * @return bool */ public function show() { header('Content-Type:' . $this->_mime); if ($this->_type == 1) { imagegif($this->_im); return true; } if ($this->_type == 2) { imagejpeg($this->_im, null, 80); return true; } if ($this->_type == 3) { imagepng($this->_im); return true; } } /** * 保存图像文件 * @param $file * @param null $quality * @return bool * @throws \Exception */ public function save($file, $quality = null) { //获取保存目的文件的扩展名 $ext = pathinfo($file, PATHINFO_EXTENSION); $ext = strtolower($ext); if (!$ext || !in_array($ext, array('jpg', 'jpeg', 'gif', 'png'))) { throw new \Exception('image save file must be jpg ,png,gif'); } if ($ext === 'gif') { imagegif($this->_im, $file); return true; } if ($ext === 'jpeg' || $ext === 'jpg') { if ($quality > 0) { if ($quality < 1) { $quality = 1; } if ($quality > 100) { $quality = 100; } imagejpeg($this->_im, $file, $quality); } else { imagejpeg($this->_im, $file); } return true; } if ($ext === 'png') { imagepng($this->_im, $file); return true; } } }style样式不是重点,先不放了然后是ajax类封装的文件:ajax.jslet $ = new class { constructor() { this.xhr = new XMLHttpRequest(); this.xhr.onreadystatechange = () => { if (this.xhr.readyState == 4 && this.xhr.status == 200) { // process response text let response = this.xhr.responseText; if (this.type == "json") { response = JSON.parse(response); } this.callback(response); } } } get(url, parameters, callback, type = "text") { // url = test.php?username=zhangsan&age=20 // parameters = let data = this.parseParameters(parameters); if (data.length > 0) { url += "?" + data; } this.type = type; this.callback = callback; this.xhr.open("GET", url, true); this.xhr.send(); } post(url, parameters, callback, type = "text") { let data = this.parseParameters(parameters); this.type = type; this.callback = callback; this.xhr.open("POST", url, true); this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); this.xhr.send(data); } parseParameters(parameters) { // username=zhangsan&age=20 let buildStr = ""; for (let key in parameters) { let str = key + "=" + parameters[key]; buildStr += str + "&"; } return buildStr.substring(0, buildStr.length - 1); } };1、首页文件:index.php<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后!--> <title>文件上传和下载</title> <!-- Bootstrap --> <link href="style/css/bootstrap.min.css" rel="stylesheet"> <link href="style/css/site.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> .projects .thumbnail .caption { height: auto; max-width: auto; } .image { margin: 10px auto; border-radius: 5px; overflow: hidden; border: 1px solid #CCC; } .image .caption P { text-align: center; } </style> </head> <body> <!--导航栏--> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand hidden-sm" href="" onclick="_hmt.push(['_trackEvent', 'navbar', 'click', 'navbar-首页'])">XX网</a> </div> <div class="navbar-collapse collapse" role="navigation"> <ul class="nav navbar-nav"> <li class="hidden-sm hidden-md"> <a href="" target="_blank"></a> </li> <li> <a href="" target="_blank"></a> </li> </ul> </div> </div> </div> <!--导航栏结束--> <!--巨幕--> <div class="jumbotron masthead"> <div class="container"> <h1>文件上传下载</h1> <h2>实现文件的上传和下载功能</h2> <p class="masthead-button-links"> <form class="form-inline" onsubmit="return false;"> <div class="form-group"> <input type="search" class="form-control keywords" id="exampleInputName2" placeholder="输入搜索内容" name="keywords" value=""> <button class="btn btn-default searchBtn" type="submit">搜索</button> <button type="button" class="btn btn-primary btn-default" data-toggle="modal" data-target="#myModal"> 上传 </button> </div> </form> </p> </div> </div> <!--巨幕结束--> <!-- 模态框 --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <form class="form-inline" action="upload_class.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="10240000" /> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">上传图片</h4> </div> <div class="modal-body"> <p>选择图片:</p><input type="file" id="image" name="test_pic[]"> <br /> <p>图片描述:</p><textarea class="form-control" cols="75" name="description" id="info"></textarea> <br /><br /> <p> 是否添加水印: <select name="mark"> <option value="1">添加</option> <option value="0">不添加</option> </select> </p> <br /> <p> 图片宽度比例: <select name="scale"> <option value="800*600">800*600</option> <option value="600*450">600*450</option> <option value="400*300">400*300</option> </select> </p> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default" name="submit" id="submit" onclick="show(this)">上传</button> <button type="reset" class="btn btn-primary">重置</button> </div> </div> </form> </div> </div> <!--模态框结束--> <div class="container projects"> <div class="projects-header page-header"> <h2>上传图片展示</h2> <p>将上传的图片展示在页面中</p> </div> <div class="row pic_body"> <!-- 使用js显示图片 --> </div> <!--分页--> <nav aria-label="Page navigation" style="text-align:center"> <ul class="pagination pagination-lg"> <!-- 使用js显示页码 --> </ul> </nav> </div> <footer class="footer container"> <div class="row footer-bottom"> <ul class="list-inline text-center"> <h4><a href="class.test.com" target="_blank">class.test.com</a> | XX网</h4> </ul> </div> </footer> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="style/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="style/js/bootstrap.min.js"></script> <script type="text/JavaScript"> function show(){ if(document.getElementById("image").value == ''){ alert('请选择图片'); } if(document.getElementById("info").value == ''){ alert('请输入图片描述'); } } </script> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> <script src="style/js/Ajax.js"></script> <script> let pageNo = 1; let kws = ''; let searchBtn = document.getElementsByClassName('searchBtn')[0]; searchBtn.onclick = function() { let search = document.getElementsByClassName('keywords')[0]; let keywords = search.value; requestData(pageNo, keywords); kws = keywords; }; let requestPage = function(page) { requestData(page, kws); pageNo = page; }; let requestData = function(page_number, keywords) { let pagination = document.getElementsByClassName('pagination')[0]; let pic_body = document.getElementsByClassName('pic_body')[0]; pic_body.innerHTML = '<p style="text-align:center"><i class="fa fa-spinner fa-spin" style="font-size:24px"></i> 加载中...</p>'; $.get('search.php', { "page": page_number, "keywords": keywords }, function(res) { let divs = ''; if (res.code == 1) { // 请求成功 res.rows.forEach(function(item) { let div = '<div class="col-sm-6 col-md-3 col-lg-4"><div class="image"><a href="' + item .path + '" target="_blank"><img class="img-responsive" src="' + item.path + '" ></a><div class="caption"><p>' + item.info + '</p></div></div></div>'; divs += div; }); pic_body.innerHTML = divs; // 加载页码导航 // previous let previousBtn = ''; if (res.page_number == 1) { previousBtn = '<li class="page-item disabled"><a class="page-link" href="javascript:requestPage(' + (res.page_number - 1) + ');">Previous</a></li>'; } else { previousBtn = '<li class="page-item"><a class="page-link" href="javascript:requestPage(' + (res .page_number - 1) + ');">Previous</a></li>'; } // next let nextBtn = ''; if (res.page_total == res.page_number) { nextBtn = '<li class="page-item disabled"><a class="page-link" href="javascript:requestPage(' + (res.page_number + 1) + ');">Next</a></li>'; } else { nextBtn = '<li class="page-item"><a class="page-link" href="javascript:requestPage(' + ( res.page_number + 1) + ');">Next</a></li>' } let pages = previousBtn; for (let page = 1; page <= res.page_total; page++) { let active = ''; if (page == res.page_number) { active = 'active'; } pages += '<li class="page-item ' + active + '"><a class="page-link" href="javascript:requestPage(' + page + ');">' + page + '</a></li>'; } pages += nextBtn; pagination.innerHTML = pages; } }, 'json'); }; requestData(1, ''); </script> </body> </html>2、图片相关功能处理:upload_class.php<?php //接收传过来的数据 $description = $_POST['description']; //描述 $mark = $_POST['mark']; //水印 $scale = $_POST['scale']; //比例 800*600 $path = ''; //图片存储路径 //根据比例获取宽高 $width = substr($scale, 0, 3); //800 $height = substr($scale, 4, 3); //600 //上传图片并存储 require('UploadFile.php'); $upload = new UploadFile('test_pic'); $upload->setDestinationDir('./uploads'); $upload->setAllowMime(['image/jpeg', 'image/gif', 'image/png']); $upload->setAllowExt(['gif', 'jpeg', 'jpg', 'png']); $upload->setAllowSize(2 * 1024 * 1024); if ($upload->upload()) { $filename = $upload->getFileName()[0]; $dir = $upload->getDestinationDir(); $path = $dir . '/' . $filename; //图片存储的实际路径 } else { var_dump($upload->getErrors()); } //根据比例调整图像 require_once './lib/Image.php'; $image = new \test\Lib\Image($path); //放大并保存 $image->resize($width, $height)->save($path); $info = getimagesize($path); //根据不同的图像type 来创建图像 switch ($info[2]) { case 1: //IMAGETYPE_GIF $image = imagecreatefromgif($path); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($path); break; case 3: $image = imagecreatefrompng($path); break; default: echo '图像格式不支持'; break; } //添加水印 if ($mark == 1) { $logo = imagecreatefrompng('./uploads/logo.png'); //添加水印 imagecopy($image, $logo, 0, 0, 0, 0, imagesx($logo), imagesy($logo)); //header('Content-type:image/png'); imagejpeg($image, $path); } $dst_image = imagecreatetruecolor($width, $height); //拷贝源图像左上角起始 imagecopy($dst_image, $image, 0, 0, 0, 0, $width, $height); imagejpeg($dst_image, $path); //存入数据库 $servername = "localhost"; $username = "root"; $password = "123456"; $dbname = "pic"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 设置 PDO 错误模式,用于抛出异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO pic(`path`, `mark`, `scale`,`info`) VALUES ('$path', '$mark', '$scale','$description')"; // 使用 exec() ,没有结果返回 $conn->exec($sql); exit("<script>alert(\"图片上传成功!\");window.location=\"index.php\";</script>"); } catch (PDOException $e) { echo $sql . "<br>" . $e->getMessage(); }3、封装好的文件上传类:UploadFile.php<?php /** * Created by http://blog.bri6.cn * User: 易航 * Date: 2022/7/03 * Time: 22:01 */ class UploadFile { const UPLOAD_ERROR = [ UPLOAD_ERR_INI_SIZE => '文件大小超出了php.ini当中的upload_max_filesize的值', UPLOAD_ERR_FORM_SIZE => '文件大小超出了MAX_FILE_SIZE的值', UPLOAD_ERR_PARTIAL => '文件只有部分被上传', UPLOAD_ERR_NO_FILE => '没有文件被上传', UPLOAD_ERR_NO_TMP_DIR => '找不到临时目录', UPLOAD_ERR_CANT_WRITE => '写入磁盘失败', UPLOAD_ERR_EXTENSION => '文件上传被扩展阻止', ]; /** * @var */ protected $field_name; /** * @var string */ protected $destination_dir; /** * @var array */ protected $allow_mime; /** * @var array */ protected $allow_ext; /** * @var */ protected $file_org_name; /** * @var */ protected $file_type; /** * @var */ protected $file_tmp_name; /** * @var */ protected $file_error; /** * @var */ protected $file_size; /** * @var array */ protected $errors; /** * @var */ protected $extension; /** * @var */ protected $file_new_name; /** * @var float|int */ protected $allow_size; /** * UploadFile constructor. * @param $keyName * @param string $destinationDir * @param array $allowMime * @param array $allowExt * @param float|int $allowSize */ public function __construct($keyName, $destinationDir = './uploads', $allowMime = ['image/jpeg', 'image/gif'], $allowExt = ['gif', 'jpeg'], $allowSize = 2 * 1024 * 1024) { $this->field_name = $keyName; $this->destination_dir = $destinationDir; $this->allow_mime = $allowMime; $this->allow_ext = $allowExt; $this->allow_size = $allowSize; } /** * @param $destinationDir */ public function setDestinationDir($destinationDir) { $this->destination_dir = $destinationDir; } /** * @param $allowMime */ public function setAllowMime($allowMime) { $this->allow_mime = $allowMime; } /** * @param $allowExt */ public function setAllowExt($allowExt) { $this->allow_ext = $allowExt; } /** * @param $allowSize */ public function setAllowSize($allowSize) { $this->allow_size = $allowSize; } /** * @return bool */ public function upload() { // 判断是否为多文件上传 $files = []; if (is_array($_FILES[$this->field_name]['name'])) { foreach ($_FILES[$this->field_name]['name'] as $k => $v) { $files[$k]['name'] = $v; $files[$k]['type'] = $_FILES[$this->field_name]['type'][$k]; $files[$k]['tmp_name'] = $_FILES[$this->field_name]['tmp_name'][$k]; $files[$k]['error'] = $_FILES[$this->field_name]['error'][$k]; $files[$k]['size'] = $_FILES[$this->field_name]['size'][$k]; } } else { $files[] = $_FILES[$this->field_name]; } foreach ($files as $key => $file) { // 接收$_FILES参数 $this->setFileInfo($key, $file); // 检查错误 $this->checkError($key); // 检查MIME类型 $this->checkMime($key); // 检查扩展名 $this->checkExt($key); // 检查文件大小 $this->checkSize($key); // 生成新的文件名称 $this->generateNewName($key); if (count((array)$this->getError($key)) > 0) { continue; } // 移动文件 $this->moveFile($key); } if (count((array)$this->errors) > 0) { return false; } return true; } /** * @return array */ public function getErrors() { return $this->errors; } /** * @param $key * @return mixed */ protected function getError($key) { return $this->errors[$key]; } protected function setFileInfo($key, $file) { // $_FILES name type temp_name error size $this->file_org_name[$key] = $file['name']; $this->file_type[$key] = $file['type']; $this->file_tmp_name[$key] = $file['tmp_name']; $this->file_error[$key] = $file['error']; $this->file_size[$key] = $file['size']; } /** * @param $key * @param $error */ protected function setError($key, $error) { $this->errors[$key][] = $error; } /** * @param $key * @return bool */ protected function checkError($key) { if ($this->file_error > UPLOAD_ERR_OK) { switch ($this->file_error) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_EXTENSION: $this->setError($key, self::UPLOAD_ERROR[$this->file_error]); return false; } } return true; } /** * @param $key * @return bool */ protected function checkMime($key) { if (!in_array($this->file_type[$key], $this->allow_mime)) { $this->setError($key, '文件类型' . $this->file_type[$key] . '不被允许!'); return false; } return true; } /** * @param $key * @return bool */ protected function checkExt($key) { $this->extension[$key] = pathinfo($this->file_org_name[$key], PATHINFO_EXTENSION); if (!in_array($this->extension[$key], $this->allow_ext)) { $this->setError($key, '文件扩展名' . $this->extension[$key] . '不被允许!'); return false; } return true; } /** * @return bool */ protected function checkSize($key) { if ($this->file_size[$key] > $this->allow_size) { $this->setError($key, '文件大小' . $this->file_size[$key] . '超出了限定大小' . $this->allow_size); return false; } return true; } /** * @param $key */ protected function generateNewName($key) { $this->file_new_name[$key] = uniqid() . '.' . $this->extension[$key]; } /** * @param $key * @return bool */ protected function moveFile($key) { if (!file_exists($this->destination_dir)) { mkdir($this->destination_dir, 0777, true); } $newName = rtrim($this->destination_dir, '/') . '/' . $this->file_new_name[$key]; if (is_uploaded_file($this->file_tmp_name[$key]) && move_uploaded_file($this->file_tmp_name[$key], $newName)) { return true; } $this->setError($key, '上传失败!'); return false; } /** * @return mixed */ public function getFileName() { return $this->file_new_name; } /** * @return string */ public function getDestinationDir() { return $this->destination_dir; } /** * @return mixed */ public function getExtension() { return $this->extension; } /** * @return mixed */ public function getFileSize() { return $this->file_size; } }4、搜索功能实现:search.php<?php // 接收请求数据 $pageNo = $_GET['page'] ?? 1; $pageSize = 9; // 接收查询参数 $keywords = $_GET['keywords'] ?? ''; $data = []; //模拟加载中的图标sleep(3); try { $pdo = new PDO( 'mysql:host=localhost:3306;dbname=pic', 'root', '123456', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] ); // 请求mysql 查询记录总数 $sql = 'SELECT count(*) AS aggregate FROM pic'; if (strlen($keywords) > 0) { $sql .= ' WHERE info like ?'; } $stmt = $pdo->prepare($sql); if (strlen($keywords) > 0) { $stmt->bindValue(1, '%' . $keywords . '%', PDO::PARAM_STR); } $stmt->execute(); $total = $stmt->fetch(PDO::FETCH_ASSOC)['aggregate']; // 计算最大页码,设置页码边界 $minPage = 1; $maxPage = ceil($total / $pageSize); // 3.6 $pageNo = max($pageNo, $minPage); $pageNo = min($pageNo, $maxPage); $offset = ($pageNo - 1) * $pageSize; $sql = "SELECT `path`,`info` FROM pic "; if (strlen($keywords) > 0) { $sql .= ' WHERE info like ?'; } $sql .= 'ORDER BY id DESC LIMIT ?, ?'; $stmt = $pdo->prepare($sql); if (strlen($keywords) > 0) { $stmt->bindValue(1, '%' . $keywords . '%', PDO::PARAM_STR); $stmt->bindValue(2, (int)$offset, PDO::PARAM_INT); $stmt->bindValue(3, (int)$pageSize, PDO::PARAM_INT); } else { $stmt->bindValue(1, (int)$offset, PDO::PARAM_INT); $stmt->bindValue(2, (int)$pageSize, PDO::PARAM_INT); } $stmt->execute(); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); $data = [ 'code' => 1, 'msg' => 'ok', 'rows' => $results, 'total_records' => (int)$total, 'page_number' => (int)$pageNo, 'page_size' => (int)$pageSize, 'page_total' => (int)$maxPage, ]; } catch (PDOException $e) { $data = [ 'code' => 0, 'msg' => $e->getMessage(), 'rows' => [], 'total_records' => 0, 'page_number' => 0, 'page_size' => (int)$pageSize, 'page_total' => 0, ]; } header('Content-type: application/json'); echo json_encode($data);4、最后数据库格式/* Navicat MySQL Data Transfer Source Server Version : 80012 Target Server Type : MYSQL Target Server Version : 80012 File Encoding : 65001 Date: 2020-01-14 16:22:49 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for pic -- ---------------------------- DROP TABLE IF EXISTS `pic`; CREATE TABLE `pic` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `path` varchar(255) DEFAULT NULL, `mark` tinyint(3) DEFAULT NULL, `scale` varchar(255) DEFAULT NULL, `info` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of pic -- ---------------------------- INSERT INTO `pic` VALUES ('1', './uploads/5e1d788084cc5.jpg', '1', '800*600', '这是测试图片1'); INSERT INTO `pic` VALUES ('2', './uploads/5e1d789766591.jpg', '1',);
2022年07月03日
87 阅读
0 评论
3 点赞
2022-06-28
PHP使用Curl函数进行远程请求案例,爬虫,可保存账户登录状态
CURL简介: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服务器等等。本文主要介绍的是php远程请求CURL(爬虫、保存登录状态)的相关内容,下面话不多说了,来一起看看详细的介绍吧GET案例:<?php /** * curl_get * @param $url * @param null $param * @param null $options * @return array */ function curl_get($url, $param = null, $options = null) { if (empty($options)) { $options = array( 'timeout' => 30, // 请求超时 'header' => array(), // 数据格式如array('Accept: */*','Accept-Encoding: gzip, deflate, br') 'cookie' => '', // cookie字符串,浏览器直接复制即可 'cookie_file' => '', // 文件路径,并要有读写权限的 'ssl' => 0, // 是否检查https协议 'referer' => null ); } else { empty($options['timeout']) && $options['timeout'] = 30; empty($options['ssl']) && $options['ssl'] = 0; } $result = array( 'code' => 0, 'msg' => 'success', 'body' => '' ); if (is_array($param)) { $param = http_build_query($param); } $url = strstr($url, '?') ? trim($url, '&') . '&' . $param : $url . '?' . $param; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // 设置url !empty($options['header']) && curl_setopt($ch, CURLOPT_HTTPHEADER, $options['header']); // 设置请求头 if (!empty($options['cookie_file']) && file_exists($options['cookie_file'])) { curl_setopt($ch, CURLOPT_COOKIEFILE, $options['cookie_file']); curl_setopt($ch, CURLOPT_COOKIEJAR, $options['cookie_file']); } else if (!empty($options['cookie'])) { curl_setopt($ch, CURLOPT_COOKIE, $options['cookie']); } curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); //curl解压gzip页面内容 curl_setopt($ch, CURLOPT_HEADER, 1); // 获取请求头 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 输出转移,不输出页面 !$options['ssl'] && curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $options['ssl']); // 禁止服务器端的验证ssl !empty($options['referer']) && curl_setopt($ch, CURLOPT_REFERER, $options['referer']); //伪装请求来源,绕过防盗 curl_setopt($ch, CURLOPT_TIMEOUT, $options['timeout']); //执行并获取内容 $output = curl_exec($ch); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($output, 0, $header_size); $output = substr($output, $header_size); //对获取到的内容进行操作 if ($output === FALSE) { $result['code'] = 1; // 错误 $result['msg'] = "CURL Error:" . curl_error($ch); } $result['header'] = $header; $result['body'] = $output; //释放curl句柄 curl_close($ch); return $result; } ?>POST案例:<?php /** * curl_post * @param $url 请求地址 * @param null $param post参数 * @param array $options 配置参数 * @return array */ function curl_post($url, $param = null, $options = array()) { if (empty($options)) { $options = array( 'timeout' => 30, 'header' => array(), 'cookie' => '', 'cookie_file' => '', 'ssl' => 0, 'referer' => null ); } else { empty($options['timeout']) && $options['timeout'] = 30; empty($options['ssl']) && $options['ssl'] = 0; } $result = array( 'code' => 0, 'msg' => 'success', 'body' => '' ); if (is_array($param)) { $param = http_build_query($param); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // 设置url !empty($options['header']) && curl_setopt($ch, CURLOPT_HTTPHEADER, $options['header']); // 设置请求头 if (!empty($options['cookie_file']) && file_exists($options['cookie_file'])) { curl_setopt($ch, CURLOPT_COOKIEFILE, $options['cookie_file']); curl_setopt($ch, CURLOPT_COOKIEJAR, $options['cookie_file']); } else if (!empty($options['cookie'])) { curl_setopt($ch, CURLOPT_COOKIE, $options['cookie']); } curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); //curl解压gzip页面内容 curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $param); curl_setopt($ch, CURLOPT_HEADER, 1); // 获取请求头 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 输出转移,不输出页面 !$options['ssl'] && curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $options['ssl']); // 禁止服务器端的验证ssl !empty($options['referer']) && curl_setopt($ch, CURLOPT_REFERER, $options['referer']); //伪装请求来源,绕过防盗 curl_setopt($ch, CURLOPT_TIMEOUT, $options['timeout']); //执行并获取内容 $output = curl_exec($ch); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($output, 0, $header_size); $output = substr($output, $header_size); //对获取到的内容进行操作 if ($output === FALSE) { $result['code'] = 1; // 错误 $result['msg'] = "CURL Error:" . curl_error($ch); } $result['header'] = $header; $result['body'] = $output; //释放curl句柄 curl_close($ch); return $result; } ?>关于php远程请求CURL(爬虫,保存登录状态)的这篇文章到此结束。其他请求类型行请参考这篇文章:PHP进行各种网络请求的方式和实现函数总结
2022年06月28日
57 阅读
0 评论
0 点赞
2022-06-28
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方法,Put方法,FTP上传,keyberos认证,HTTP上传,代理服务器,cookies,用户名/密码认证,下载文件断点续传,上传文件断点续传,HTTP代理服务器管道,甚至它支持IPv6,scoket5代理服务器,通过HTTP代理服务器上传文件到FTP服务器等。,所以我们在开发中尽量使用curl做网络请求,不管是简单的还是复杂的。二、file_get_contents发送网络请求示例file_get_contents(path,include_path,context,start,max_length);参数描述path必需。规定要读取的文件。include_path可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 "1"。context可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。若使用 null,则忽略。start可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。max_length可选。规定读取的字节数。该参数是 PHP 5.1 新加的。一般用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(); // '' // 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扩展库,用起来也很方便。
2022年06月28日
63 阅读
0 评论
2 点赞