REC
首页
文章分类
源码资源
技术教程
程序软件
文创娱乐
玄学修炼
关于我们
其他页面
网站统计
友情链接
用户留言
高清壁纸
关于易航
热门文章
Joe再续前缘主题 - 搭建本站同款网站
易航网址导航系统 – 功能强大,轻量易用
JsonDb-PHP轻量级文件数据库系统
Typecho一键调整网站为冬天情景插件
V免签全开源免签约码支付系统(支持:支付宝 微信 QQ)
标签搜索
PHP
Web前端
网站源码
PHP源码
Typecho
Typecho插件
课程资料
Windows程序
Android软件
武术内功
HTML源码
Web
Joe主题
Python
Windows
国漫
网络协议
MySQL
NodeJs
小说
发布
登录
注册
找到
51
篇与
PHP
相关的结果
- 第 5 页
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源码
# PHP
易航
3年前
4
129
2
2022-08-19
JsonDb-PHP轻量级文件数据库系统
介绍 JsonDb 是一款由原生 PHP 实现的非关系型轻量级 JSON 文件数据库。如果你需要存储各种基础类的数据,或者一个站点内有多个小项目,那么 JsonDb 就是你最佳的选择。它包括查询、新增、更新、删除等对数据的基本操作,适合存储数据量不大的数据 使用帮助文档:https://yepydvmpxo.k.topthink.com/@json-db/ 软件架构 由纯原生 PHP 实现的 JSON 文件数据库,将数据存储为 JSON 格式,不占用 MySql 资源纯以读写文件的形式查询数据库,用法类似于 ThinkPHP 的查询。 安装教程 composer require jsondb/jsondb:dev-master使用说明 use JsonDb\JsonDb\Db; // composer自动加载 require 'vendor/autoload.php'; // 默认关闭数据压缩、加密并开启调试模式,可使用自定义配置 // 自定义配置项 具体配置请参考文档:https://yepydvmpxo.k.topthink.com/@json-db/ $json_path = $_SERVER['DOCUMENT_ROOT'] . 'content' . DIRECTORY_SEPARATOR . 'JsonDb'; Db::setConfig([ 'path' => $json_path, // 数据存储路径(必须配置) 'file_suffix' => '.json', // 文件后缀名 'debug' => true, // 调试模式 'encode' => null, // 数据加密函数 'decode' => null, // 数据解密函数 ]); // 添加单条数据 Db::name('table_name')->insert([ 'a' => 5, 'b' => "测试5" ]); // 添加多条数据 Db::name('table_name')->insertAll([ [ 'a' => 5, 'b' => "测试5" ], [ 'c' => 1, 'b' => "测试" ] ]); // 删除一行中的部分数据 Db::name('table_name')->where('b', '测试3')->delete(['a', 'b']); // 删除一行数据 Db::name('table_name')->where('b', '测试3')->deleteAll(); // 更新数据 Db::name('table_name')->where('b', '测试4')->update(['c' => '测试测试']); // 根据ID查询数据 Db::name('table_name')->where('id', 0)->find(); // 查询单条数据 Db::name('table_name')->where('b', '测试')->find(); // 查询多条数据 Db::name('table_name')->where('b', '测试4')->select(); // 查询所有数据 Db::name('table_name')->selectAll(); // 自定义查询表达式 Db::name('table_name')->where('id', '>', 4)->select(); // 链式where Db::name('table_name')->where('id', 1)->where('a', 2)->select(); // 自定义判断条件 $select = Db::name('table_name')->where('`field_id` == 0 || `field_b` == `测试4`')->select(); // 字段LIKE查询 Db::name('table_name')->whereLike('b', '%测试')->select(); // 限制结果数量 Db::name('user')->where('status', 1)->limit(10)->select(); // 限制每次最大写入数量 Db::name('user')->limit(100)->insertAll($userList);
技术教程
# PHP
易航
3年前
0
1,546
4
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; }
技术教程
# PHP
易航
3年前
0
151
0
2022-08-13
PHP图片上传代码
PHP上传图片完整实 HTML部分 <html> <head> <meta charset="utf-8"> <title>银狐笔记图片上传实例</title> </head> <body> <form action="up.php" method="post" enctype="multipart/form-data"> <label for="file">文件名:</label> <input type="file" name="file" id="file"><br> <input type="submit" name="submit" value="提交"> </form> </body> </html>form表单提交数据给PHP文件,enctype="multipart/form-data" ,这个代码不能少,获取文件类型。 PHP代码 <?php // 允许上传的图片后缀 $allowedExts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $_FILES["file"]["name"]); echo $_FILES["file"]["size"]; $extension = end($temp); // 获取文件后缀名 if ( ( ($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png") ) && ($_FILES["file"]["size"] < 204800) // 小于 200 kb && in_array($extension, $allowedExts) ) { if ($_FILES["file"]["error"] > 0) { echo "错误:: " . $_FILES["file"]["error"] . "<br>"; } else { echo "上传文件名: " . $_FILES["file"]["name"] . "<br>"; echo "文件类型: " . $_FILES["file"]["type"] . "<br>"; echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"] . "<br>"; // 判断当前目录下的 upload 目录是否存在该文件 // 如果没有 upload 目录,你需要创建它,upload 目录权限为 777 if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " 文件已经存在。 "; } else { // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下 move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "文件存储在: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "非法的文件格式"; }
技术教程
# PHP
易航
3年前
1
156
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' ]);带Cookie curl('http://blog.bri6.cn', [ 'cookie' => 'cookie内容' ]);模拟refer curl('http://blog.bri6.cn', [ 'refer' => 'https://xxx' ]);模拟UA curl('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 ]);
技术教程
# PHP
易航
3年前
0
80
1
2022-08-08
PHP对字符串的六种加密解密方法
一、 function encryptDecrypt($key, $string, $decrypt) { if ($decrypt) { $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12"); return $decrypted; } else { $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key)))); return $encrypted; } } //加密:"z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=" echo encryptDecrypt('password', 'Helloweba欢迎您', 0); //解密:"Helloweba欢迎您" echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=', 1);二、 //加密函数 function lock_url($txt, $key = 'liiu') { $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+"; $nh = rand(0, 64); $ch = $chars[$nh]; $mdKey = md5($key . $ch); $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7); $txt = base64_encode($txt); $tmp = ''; $i = 0; $j = 0; $k = 0; for ($i = 0; $i < strlen($txt); $i++) { $k = $k == strlen($mdKey) ? 0 : $k; $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64; $tmp .= $chars[$j]; } return urlencode($ch . $tmp); } //解密函数 function unlock_url($txt, $key = 'liiu') { $txt = urldecode($txt); $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+"; $ch = $txt[0]; $nh = strpos($chars, $ch); $mdKey = md5($key . $ch); $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7); $txt = substr($txt, 1); $tmp = ''; $i = 0; $j = 0; $k = 0; for ($i = 0; $i < strlen($txt); $i++) { $k = $k == strlen($mdKey) ? 0 : $k; $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]); while ($j < 0) $j += 64; $tmp .= $chars[$j]; } return base64_decode($tmp); }三、改进后的算法 //加密函数 function lock_url($txt, $key = 'str') { $txt = $txt . $key; $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+"; $nh = rand(0, 64); $ch = $chars[$nh]; $mdKey = md5($key . $ch); $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7); $txt = base64_encode($txt); $tmp = ''; $i = 0; $j = 0; $k = 0; for ($i = 0; $i < strlen($txt); $i++) { $k = $k == strlen($mdKey) ? 0 : $k; $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64; $tmp .= $chars[$j]; } return urlencode(base64_encode($ch . $tmp)); } //解密函数 function unlock_url($txt, $key = 'str') { $txt = base64_decode(urldecode($txt)); $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+"; $ch = $txt[0]; $nh = strpos($chars, $ch); $mdKey = md5($key . $ch); $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7); $txt = substr($txt, 1); $tmp = ''; $i = 0; $j = 0; $k = 0; for ($i = 0; $i < strlen($txt); $i++) { $k = $k == strlen($mdKey) ? 0 : $k; $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]); while ($j < 0) $j += 64; $tmp .= $chars[$j]; } return trim(base64_decode($tmp), $key); }四、 function passport_encrypt($txt, $key = 'liiu') { srand((float)microtime() * 1000000); $encrypt_key = md5(rand(0, 32000)); $ctr = 0; $tmp = ''; for ($i = 0; $i < strlen($txt); $i++) { $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]); } return urlencode(base64_encode(passport_key($tmp, $key))); } function passport_decrypt($txt, $key = 'liiu') { $txt = passport_key(base64_decode(urldecode($txt)), $key); $tmp = ''; for ($i = 0; $i < strlen($txt); $i++) { $md5 = $txt[$i]; $tmp .= $txt[++$i] ^ $md5; } return $tmp; } function passport_key($txt, $encrypt_key) { $encrypt_key = md5($encrypt_key); $ctr = 0; $tmp = ''; for ($i = 0; $i < strlen($txt); $i++) { $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; $tmp .= $txt[$i] ^ $encrypt_key[$ctr++]; } return $tmp; } $txt = "1"; $key = "testkey"; $encrypt = passport_encrypt($txt, $key); $decrypt = passport_decrypt($encrypt, $key); echo $encrypt . "<br>"; echo $decrypt . "<br>";五、非常给力的authcode加密函数,Discuz!经典代码(带详解) //函数authcode($string, $operation, $key, $expiry)中的$string:字符串,明文或密文;$operation:DECODE表示解密,其它表示加密;$key:密匙;$expiry:密文有效期。 function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙 $ckey_length = 4; // 密匙 $key = md5($key ? $key : $GLOBALS['discuz_auth_key']); // 密匙a会参与加解密 $keya = md5(substr($key, 0, 16)); // 密匙b会用来做数据完整性验证 $keyb = md5(substr($key, 16, 16)); // 密匙c用于变化生成的密文 $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : ''; // 参与运算的密匙 $cryptkey = $keya . md5($keya . $keyc); $key_length = strlen($cryptkey); // 明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b), //解密时会通过这个密匙验证数据完整性 // 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确 $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string; $string_length = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); // 产生密匙簿 for ($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } // 用固定的算法,打乱密匙簿,增加随机性,好像很复杂,实际上对并不会增加密文的强度 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 == 'DECODE') { // 验证数据有效性,请看未加密明文的格式 if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) { return substr($result, 26); } else { return ''; } } else { // 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因 // 因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码 return $keyc . str_replace('=', '', base64_encode($result)); } } $str = 'abcdef'; $key = 'www.helloweba.com'; echo authcode($str, 'ENCODE', $key, 0); //加密 $str = '56f4yER1DI2WTzWMqsfPpS9hwyoJnFP2MpC8SOhRrxO7BOk'; echo authcode($str, 'DECODE', $key, 0); //解密 六、 /** * $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)); } }
技术教程
# PHP
易航
3年前
0
639
4
2022-07-17
PHP各种常用函数方法封装
当前日期和时间 /** * 当前日期和时间 * @return string */ function date_time(): string { return date('Y-m-d H:i:s'); }动态创建Element元素 /** * 动态创建Element元素 * * @param string $element * @return ElementBuilder */ function element($element) { return new ElementBuilder($element); } /** * @package ElementBuilder * @description 动态创建HTML的Element标签 * @author 易航 * @version 1.0 * @link http://blog.bri6.cn */ class ElementBuilder { private $options = [ 'element' => 'div', 'inner' => null, 'attributes' => [] ]; private function attributes($attributes) { return FormBuilder::attributes($attributes); } public function __construct($element) { $this->options['element'] = $element; } /** * 设置标签内部的HTML内容 * @param $innerHTML 要设置的标签HTML内容 * @return $this */ public function innerHTML($innerHTML) { $this->options['inner'] = $innerHTML; return $this; } /** * 设置标签内部的文本内容 * @param $innerText 要设置的标签文本内容 * @return $this */ public function innerText($innerText) { $this->options['inner'] = empty($innerText) ? $innerText : htmlentities($innerText); return $this; } /** * 批量设置标签的属性 * @param $attributes * @return $this */ public function attr($attributes, $content = null) { if (is_array($attributes)) { foreach ($attributes as $key => $value) { $this->options['attributes'][$key] = $value; } } if (is_string($attributes)) { $this->options['attributes'][$attributes] = $content; } return $this; } /** * 获取生成的HTML内容 * @return string */ public function get($html = null) { $this->innerHTML($html); $element = $this->options['element']; $content = $this->options['inner']; $attributes = $this->attributes($this->options['attributes']); if ($content === false) { $html = "<$element$attributes />"; } else { $html = "<$element$attributes>$content</$element>"; } return $html; } public function __toString() { return $this->get($this->options['inner']); } }解压ZIP文件 function zipExtract($src, $dest) { // 通过ZipArchive的对象处理zip文件 $zip = new ZipArchive(); //新建一个ZipArchive的对象 /* $zip->open这个方法的参数表示处理的zip文件名。 如果对zip文件对象操作成功,$zip->open这个方法会返回TRUE */ if ($zip->open($src) === true) { $zip->extractTo($dest); //假设解压缩到$dest路径文件夹的子文件夹php $zip->close(); //关闭处理的zip文件 return true; } return false; }获取指定目录下的文件和目录列表 /** * 获取指定目录下的文件和目录列表 * * @param string $directory 要扫描的目录 * @return DirScanner */ function scan_dir(string $directory) { return new DirScanner($directory); } /** * 获取指定目录下的文件和目录列表 */ class DirScanner { private array $list; private string $directory; /** * @param string $directory 要扫描的目录 */ public function __construct(string $directory) { $this->directory = str_replace(['//', '\\\\'], ['/', '\\'], $directory); $this->directory = preg_match('/^\/|\\\$/', $this->directory) ? $this->directory : $this->directory . DIRECTORY_SEPARATOR; $this->list = array_values(array_diff(scandir($directory), ['.', '..'])); } /** * 只获取文件 */ public function files(array $suffixes = []): array { return $this->filter($suffixes, 'is_file'); } /** * 只获取目录 */ public function dirs(): array { return $this->filter([], 'is_dir'); } /** * 获取所有文件和目录 */ public function all(): array { return $this->list; } /** * 过滤列表 */ private function filter(array $suffixes, callable $callback): array { $directory = $this->directory; return array_filter($this->list, function ($item) use ($directory, $suffixes, $callback) { $path = $directory . $item; if (!empty($suffixes) && is_file($path)) { $extension = pathinfo($item, PATHINFO_EXTENSION); if (!in_array($extension, $suffixes)) return false; } return $callback($path); }); } }删除文件或文件夹 /** * 删除文件或文件夹 * * @param string $directory 目录的路径。 * @param resource $context 上下文流(context stream) resource * @return bool */ function delete_directory(string $directory, $context = null) { if (is_dir($directory)) { $objects = scandir($directory); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($directory . DIR_SEP . $object)) { delete_directory($directory . DIR_SEP . $object); } else { unlink($directory . DIR_SEP . $object); } } } rmdir($directory, $context); } elseif (is_file($directory)) { unlink($directory, $context); } }多维数组转对象 /** * 多维数组转对象 * @param array $d * @return object */ function array_to_object(array $d): object { if (is_array($d)) { $json = json_encode($d); return json_decode($json); } else { return $d; } }多维对象转数组 /** * 多维对象转数组 * @param object|array $d * @return array */ function object_to_array($d) { if (is_object($d)) { $d = get_object_vars($d); // 获取给定对象的属性 } if (is_array($d)) { $function = __FUNCTION__; return array_map("self::$function", $d); } else { return $d; } }发送电子邮件 /** * 发送电子邮件 * @access public * @param string $title 邮件标题 * @param string $subtitle 邮件副标题 * @param string $content 邮件内容 * @param string $email 不填写则默认发送系统配置中的邮箱,优先程度:配置收件人>发信邮箱 * @return bool|object */ function send_mail($title, $subtitle, $content, $email = null) { $site = options('site'); $mail = options('mail'); if (empty($email)) { $email = empty($mail['recv']) ? $mail['account'] : $mail['recv']; } $PHPMailer = new \PHPMailer\PHPMailer\PHPMailer(); $language = $PHPMailer->setLanguage('zh_cn'); if (!$language) { return 'PHPMailer语言文件zh_cn加载失败'; } $PHPMailer->isSMTP(); $PHPMailer->SMTPAuth = true; $PHPMailer->CharSet = 'UTF-8'; $PHPMailer->SMTPSecure = $mail['secure']; // 允许 TLS 或者ssl协议 $PHPMailer->Host = $mail['smtp']; // SMTP服务器 $PHPMailer->Port = $mail['port']; // 服务器端口 25 或者465 $PHPMailer->FromName = $site['title']; //发件人昵称 $PHPMailer->Username = $mail['account']; //邮箱账号 $PHPMailer->From = $mail['account']; //邮箱账号 $PHPMailer->Password = $mail['pwd']; //邮箱密码 $PHPMailer->isHTML(true); $html = '<!DOCTYPE html><html lang="zh-cn"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"></head><body><style>.container{width:95%;margin:0 auto;border-radius:8px;font-family:"Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;box-shadow:0 2px 12px 0 rgba(0,0,0,0.1);word-break:break-all}.title{color:#fff;background:linear-gradient(-45deg,rgba(9,69,138,0.2),rgba(68,155,255,0.7),rgba(117,113,251,0.7),rgba(68,155,255,0.7),rgba(9,69,138,0.2));background-size:400%400%;background-position:50%100%;padding:15px;font-size:15px;line-height:1.5}</style><div class="container"><div class="title">{title}</div><div style="background: #fff;padding: 20px;font-size: 13px;color: #666;"><div style="margin-bottom: 20px;line-height: 1.5;">{subtitle}</div><div style="padding: 15px;margin-bottom: 20px;line-height: 1.5;background: repeating-linear-gradient(145deg, #f2f6fc, #f2f6fc 15px, #fff 0, #fff 25px);">{content}</div><div style="line-height: 2">请注意:此邮件由系统自动发送,请勿直接回复。<br>若此邮件不是您请求的,请忽略并删除!</div></div></div></body></html>'; $PHPMailer->Body = strtr( $html, [ "{title}" => $title . ' - ' . $site['title'], "{subtitle}" => $subtitle, "{content}" => $content, ] ); $PHPMailer->addAddress($email); $PHPMailer->Subject = $title . ' - ' . $site['title']; if ($PHPMailer->send()) { return true; } else { return $PHPMailer->ErrorInfo; } }获取配置信息 function options($name = false, $value = false) { if ($name === false && $value == false) { return Options::all(); } if (func_num_args() == 1) { returnOptions::get($name); } return Options::save($name, $value); } class Options { private static $options = null; public static function initialize() { if (is_null(self::$options)) { $select = Db::name('options')->select(); self::$options = []; foreach ($select as $value) { self::$options[$value['name']] = $value['value']; } } } public static function get($name) { $name_list = explode('.', $name); // 将路径分解成键名数组 $value = self::$options; // 初始化$value为数组的根 // 遍历键名数组,逐级深入到数组中 foreach ($name_list as $name_value) { if (isset($value[$name_value])) { $value = $value[$name_value]; // 如果键存在,更新$value } else { return null; // 如果键不存在,返回null或者你可以选择抛出异常 } } return $value; // 返回最终找到的值 } public static function all() { return self::$options; } public static function save(string $name, $value) { if (array_key_exists($name, self::$options)) { $save = self::update($name, $value); } else { $save = self::insert($name, $value); } // 保存虚拟模型数据 self::model($name, $value); return $save; } public static function insert(string $name, $value) { // 插入虚拟模型数据 self::model($name, $value); // 插入数据库数据 return Db::name('options')->insert(['name' => $name, 'value' => $value]); } /** * 设置虚拟模型数据 */ public static function model(string $name, $value) { self::$options[$name] = $value; return true; } public static function update(string $name, $value) { // 更新虚拟模型数据 self::model($name, $value); // 更新数据库数据 return Db::name('options')->where('name', $name)->update(['value' => $value]); } }以数组的形式返回关于文件路径的信息 pathinfo(path, options); /** 返回的数组元素如下: ['dirname']: 目录路径 ['basename']: 文件名 ['extension']: 文件后缀名 ['filename']: 不包含后缀的文件名 **/ // path:规定要检查的路径。 /** options: PATHINFO_DIRNAME - 只返回 dirname PATHINFO_BASENAME - 只返回 basename PATHINFO_EXTENSION - 只返回 extension PATHINFO_FILENAME - 只返回 filename **/获取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; } ?>多维数组降维 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; }字符串加密解密 /** * $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)); } }
技术教程
# PHP
易航
3年前
0
217
2
2022-07-10
PHP对API接口请求进行限流的几种算法
接口限流的意义 那么什么是限流呢?顾名思义,限流就是限制流量,包括一定时间内的并发流量和总流量。 就像你有一个GB流量的宽带包,用完就没了,所以控制好自己的使用频率和单次使用的总消费。 通过限流,我们可以很好地控制系统的qps,从而达到保护系统或者接口服务器稳定的目的。 接口限流的常用算法 1、计数器法 计数器法是限流算法里最简单也是最容易实现的一种算法。 比如我们规定,对于A接口来说,我们1分钟的访问次数不能超过100个。那么我们可以这么做:在一开始的时候,我们可以设置一个计数器counter,每当一个请求过来的时候,counter就加1,如果counter的值大于100并且该请求与第一个请求的间隔时间还在1分钟之内,那么说明请求数过多; 如果该请求与第一个请求的间隔时间大于1分钟,且counter的值还在限流范围内,那么就重置counter。 代码如下: class CounterDemo { private $first_request_time; private $request_count = 0; //已请求的次数 public $limit = 100; //时间窗口内的最大请求数 public $interval = 60; //时间窗口 s public function __construct() { $this->first_request_time = time(); } public function grant() { $now = time(); if ($now < $this->first_request_time + $this->interval) { //时间窗口内 if ($this->request_count < $this->limit) { $this->request_count++; return true; } else { return false; } } else { //超出前一个时间窗口后, 重置第一次请求时间和请求总次数 $this->first_request_time = $now; $this->request_count = 1; return true; } } } $m = new CounterDemo(); $n_success = 0; for ($i = 0; $i < 200; $i++) { $rt = $m->grant(); if ($rt) { $n_success++; } } echo '成功请求 ' . $n_success . ' 次';计数器算法很简单,但是有个严重的bug: 一个恶意用户在0:59时瞬间发送了100个请求,然后再1:00时又瞬间发送了100个请求,那么这个用户在2秒内发送了200个请求。 上面我们规定1分钟最多处理100个请求, 也就是每秒1.7个请求。用户通过在时间窗口的重置节点处突发请求, 可以瞬间超过系统的承载能力,导致系统挂起或宕机。 上面的问题,其实是因为我们统计的精度太低造成的。那么如何很好地处理这个问题呢?或者说,如何将临界问题的影响降低呢?我们可以看下面的滑动窗口算法。 图片 上图中,我们把一个时间窗口(一分钟)分成6份,每份(小格)代表10秒。每过10秒钟我们就把时间窗口往右滑动一格, 每一个格子都有自己独立的计数器。 比如一个请求在0:35秒到达的时候,就会落在0:30-0:39这个区间,并将此区间的计数器加1。 从上图可以看出, 0:59到达的100个请求会落在0:50-0:59这个灰色的格子中, 而1:00到达的100个请求会落在黄色的格子中。 而在1:00时间统计时, 窗口会往右移动一格,那么此时的时间窗口内的请求数量一共是200个,超出了限制的100个,触发了限流,后面的100个请求被抛弃或者等待。 如果我们把窗口时间划分越多, 比如60格,每格1s, 那么限流统计会更精确。 2、漏桶算法 (Leaky Bucket) 漏桶算法(Leaky Bucket): 平滑网络上的突发流量。使其整流为一个稳定的流量。 图片 有一个固定容量的桶,有水流进来,也有水流出 去。对于流进来的水来说,我们无法预计一共有多少水会流进来,也无法预计水流的速度。但是对于流出去的水来说,这个桶可以固定水流出的速率。当桶满了之后,多余的水将会溢出(多余的请求会被丢弃)。 简单的算法实现代码: class LeakyBucketDemo { private $last_req_time; //上一次请求的时间 public $capacity; //桶的容量 public $rate; //水漏出的速度(个/秒) public $water; //当前水量(当前累积请求数) public function __construct() { $this->last_req_time = time(); $this->capacity = 100; $this->rate = 20; $this->water = 0; } public function grant() { $now = time(); $water = max(0, $this->water - ($now - $this->last_req_time) * $this->rate); // 先执行漏水,计算剩余水量 $this->water = $water; $this->last_req_time = $now; if ($water < $this->capacity) { // 尝试加水,并且水还未满 $this->water += 1; return true; } else { // 水满,拒绝加水 return false; } } } $m = new LeakyBucketDemo(); $n_success = 0; for ($i = 0; $i < 500; $i++) { $rt = $m->grant(); if ($rt) { $n_success++; } if ($i > 0 && $i % 100 == 0) { //每发起100次后暂停1s echo '已发送', $i, ', 成功 ', $n_success, ', sleep' . PHP_EOL; sleep(1); } } echo '成功请求 ' . $n_success . ' 次';3、令牌桶算法 (Token Bucket) 令牌桶算法比漏桶算法稍显复杂。首先,我们有一个固定容量的桶,桶里存放着令牌(token)。桶一开始是空的(可用token数为0),token以一个固定的速率r往桶里填充,直到达到桶的容量,多余的令牌将会被丢弃。每当一个请求过来时,就会尝试从桶里移除一个令牌,如果没有令牌的话,请求无法通过。 实现代码如下: class TokenBucketDemo { private $last_req_time; //上次请求时间 public $capacity; //桶的容量 public $rate; //令牌放入的速度(个/秒) public $tokens; //当前可用令牌的数量 public function __construct() { $this->last_req_time = time(); $this->capacity = 100; $this->rate = 20; $this->tokens = 100; //开始给100个令牌 } public function grant() { $now = time(); $tokens = min($this->capacity, $this->tokens + ($now - $this->last_req_time) * $this->rate); // 计算桶里可用的令牌数 $this->tokens = $tokens; $this->last_req_time = $now; if ($this->tokens < 1) { // 若剩余不到1个令牌,则拒绝 return false; } else { // 还有令牌,领取1个令牌 $this->tokens -= 1; return true; } } } $m = new TokenBucketDemo(); $n_success = 0; for ($i = 0; $i < 500; $i++) { $rt = $m->grant(); if ($rt) { $n_success++; } if ($i > 0 && $i % 100 == 0) { //每发起100次后暂停1s echo '已发送', $i, ', 成功 ', $n_success, ', sleep' . PHP_EOL; sleep(1); } } echo '成功请求 ' . $n_success . ' 次';我们可以使用redis的队列作为令牌桶容器使用,使用lPush(入队),rPop(出队),实现令牌加入与消耗的操作。 TokenBucket.php <?php /** * PHP基于Redis使用令牌桶算法实现接口限流,使用redis的队列作为令牌桶容器,入队(lPush)出队(rPop)作为令牌的加入与消耗操作。 * public add 加入令牌 * public get 获取令牌 * public reset 重设令牌桶 * private connect 创建redis连接 */ class TokenBucket { // class start private $_config; // redis设定 private $_redis; // redis对象 private $_queue; // 令牌桶 private $_max; // 最大令牌数 /** * 初始化 * @param Array $config redis连接设定 */ public function __construct($config, $queue, $max) { $this->_config = $config; $this->_queue = $queue; $this->_max = $max; $this->_redis = $this->connect(); } /** * 加入令牌 * @param Int $num 加入的令牌数量 * @return Int 加入的数量 */ public function add($num = 0) { // 当前剩余令牌数 $curnum = intval($this->_redis->lSize($this->_queue)); // 最大令牌数 $maxnum = intval($this->_max); // 计算最大可加入的令牌数量,不能超过最大令牌数 $num = $maxnum >= $curnum + $num ? $num : $maxnum - $curnum; // 加入令牌 if ($num > 0) { $token = array_fill(0, $num, 1); $this->_redis->lPush($this->_queue, ...$token); return $num; } return 0; } /** * 获取令牌 * @return Boolean */ public function get() { return $this->_redis->rPop($this->_queue) ? true : false; } /** * 重设令牌桶,填满令牌 */ public function reset() { $this->_redis->delete($this->_queue); $this->add($this->_max); } /** * 创建redis连接 * @return Link */ private function connect() { try { $redis = new Redis(); $redis->connect($this->_config['host'], $this->_config['port'], $this->_config['timeout'], $this->_config['reserved'], $this->_config['retry_interval']); if (empty($this->_config['auth'])) { $redis->auth($this->_config['auth']); } $redis->select($this->_config['index']); } catch (RedisException $e) { throw new Exception($e->getMessage()); return false; } return $redis; } } ?>令牌的假如与消耗: <?php /** * 演示令牌加入与消耗 */ require 'TokenBucket.php'; // redis连接设定 $config = array( 'host' => 'localhost', 'port' => 6379, 'index' => 0, 'auth' => '', 'timeout' => 1, 'reserved' => NULL, 'retry_interval' => 100, ); // 令牌桶容器 $queue = 'mycontainer'; // 最大令牌数 $max = 5; // 创建TrafficShaper对象 $tokenBucket = new TokenBucket($config, $queue, $max); // 重设令牌桶,填满令牌 $tokenBucket->reset(); // 循环获取令牌,令牌桶内只有5个令牌,因此最后3次获取失败 for ($i = 0; $i < 8; $i++) { var_dump($tokenBucket->get()); } // 加入10个令牌,最大令牌为5,因此只能加入5个 $add_num = $tokenBucket->add(10); var_dump($add_num); // 循环获取令牌,令牌桶内只有5个令牌,因此最后1次获取失败 for ($i = 0; $i < 6; $i++) { var_dump($tokenBucket->get()); } ?>
技术教程
# PHP
易航
3年前
0
169
2
2022-07-09
PHP8.1的10个新特性和性能改进
PHP 8.1现已推出,它带来了新的特性和性能改进——最令人向往的是新的JIT编译器。于2021年11月25日推出。 我们将详细演示PHP 8.1提供的10大特性,以便您可以开始在项目中使用它们,并改善您的PHP体验。初学者和有经验的开发人员可以从这篇文章中受益。 PHP图片 8.1 提供的 10 大功能 枚举 Fiber(纤维) never 返回类型 readonly 属性 final 类常量 新的 array_is_list() 函数 新的 fsync() 和 fdatasync() 函数 对字符串键数组解包的支持 $_FILES 新的用于目录上传的 full_path 键 新的 IntlDatePatternGenerator 类 1. 枚举 PHP 8.1 添加了对枚举的支持,简写为 enum 。它是一种逐项类型,包含固定数量的可能值。请参阅以下代码片段以了解如何使用枚举。 <?php /** * Declare an enumeration. * It can also contain an optional 'string' or 'int' value. This is called backed Enum. * Backed enums (if used) should match the following criteria: * - Declare the scalar type, whether string or int, in the Enum declaration. * - All cases have values. * - All cases contain the same scalar type, whether string or int. * - Each case has a unique value. */ enum UserRole: string { case ADMIN = '1'; case GUEST = '2'; case WRITER = '3'; case EDITOR = '4'; } /** * You can access a case by using * the '::' scope resolution operator. * And, to get the name of the enum case, you * can use the '->' followed by the attribute 'name'. */ echo UserRole::WRITER->name; /** * To get the value of the enum case, you can * use the '->' followed by the attribute 'value'. */ echo UserRole::WRITER->value; ?>2. Fiber(纤维) PHP 8.1 添加了对 Fiber 的支持,这是一个低级组件,允许在 PHP 中执行并发代码。Fiber 是一个代码块,它包含自己的变量和状态堆栈。这些 Fiber 可以被视为应用程序线程,可以从主程序启动。 一旦启动,主程序将无法挂起或终止 Fiber。它只能从 Fiber 代码块内部暂停<或终止。在 Fiber 挂起后,控制权再次返回到主程序,它可以从挂起的点继续执行 Fiber。 Fiber 本身不允许同时执行多个 Fiber 或主线程和一个 Fiber。但是,对于 PHP 框架来说,高效管理执行堆栈并允许异步执行是一个巨大的优势。 请参阅以下代码片段以了解如何使用 Fiber <?php /** * Initialize the Fiber. */ $fiber = new Fiber(function (): void { /** * Print some message from inside the Fiber. * Before the Fiber gets suspended. */ echo "Welcome to Fiber!\n"; /** * Suspend the Fiber. */ Fiber::suspend(); /** * Print some message from inside the Fiber. * After the Fiber gets resumed. */ echo "Welcome back to Fiber!\n"; }); /** * Print a message before starting a Fiber. */ echo "Starting a Fiber\n"; /** * Start the Fiber. */ $fiber->start(); /** * Fiber has been suspened from the inside. * Print some message, and then resume the Fiber. */ echo "Fiber has been suspended\n"; echo "Resuming the Fiber\n"; /** * Resume the Fiber. */ $fiber->resume(); /** * End of the example. */ echo "Fiber completed execution\n"; ?>3. never 返回类型 PHP 8.1 添加了名为 never 的返回类型。该 never 类型可用于指示函数将在执行一组指定的任务后终止程序执行。这可以通过抛出异常、调用 exit() 或 die() 函数来完成。 never 返回类型类似于 void 返回类型。但是,void 返回类型在函数完成一组指定的任务后继续执行。 请参阅以下代码片段以了解如何使用 never 返回类型 <?php /** * Route Class */ class Route { /** * Constructor of the class * @return void */ public function __construct() { } /** * Redirect To a Page * This function redirects to an URL specified by the user. * @method redirect() * @param string $url * @param integer $httpCode * @author Tara Prasad Routray <someemailaddress@example.com> * @access public * @return never */ public static function redirect($url, $httpCode = 301): never { /** * Redirect to the URL specified. */ header("Location: {$url}", true, $httpCode); die; } } Route::redirect('https://www.google.com'); ?>4. readonly 属性 PHP 8.1 添加了名为 readonly 的类属性。已声明为只读的类属性只能初始化一次。里面设置的值不能改变。如果尝试强行更新该值,应用程序将抛出错误。请参阅以下代码片段以了解如何使用只读属性。 <?php /** * User Class */ class User { /** * Declare a variable with readonly property. * @var $authUserID * @access public */ public readonly int $authUserID; /** * Constructor of the class. * @param integer $userID * @return void */ public function __construct($userID) { /** * Change the value of the property as specified. * Updating the value of readonly properties are * allowed only through the constructor. */ $this->authUserID = $userID; } /** * Update Auth User ID * This function tries to update the readonly property (which is not allowed). * @method updateAuthUserID() * @param integer $userID * @author Tara Prasad Routray <someemailaddress@example.com> * @access public * @return void */ public function updateAuthUserID($userID) { /** * Change the value of the property as specified. * Executing this function will throw the following error; * PHP Fatal error: Uncaught Error: Cannot modify readonly property User::$authUserID */ $this->authUserID = $userID; } } /** * Initialize the class and update the value of the readonly property. */ $user = new User(30); /** * Print the readonly property value. * This will print 30. */ echo $user->authUserID; /** * Call another function inside the class and try to update the class property. */ $user->updateAuthUserID(50); /** * Print the readonly property value. */ echo $user->authUserID; ?>5. final 类常量 PHP 8.1 添加了对名为 final 的类常量的支持。最终类常量不能被修改,即使是通过继承,这意味着它们不能被子类扩展或覆盖。 这个标志不能用于私有常量,因为它不能在类之外被访问。声明 final 和 private 常量将导致致命错误。 请参阅以下代码片段以了解如何使用最终标志 <?php /** * UserRole Class */ class UserRole { /** * Declare a final class constant with a value. */ final public const ADMIN = '1'; } /** * User Class extending the UserRole Class */ class User extends UserRole { /** * Declare another constant with the same name * as of the parent class to override the value. * * Note: Overriding the value will throw the following error: * PHP Fatal error: User::ADMIN cannot override final constant UserRole::ADMIN */ public const ADMIN = '2'; } ?>6. 新的 array_is_list() 函数 PHP 8.1 添加了名为 array_is_list() 的数组函数。它标识指定的数组是否具有从 0 开始的所有连续整数。如果数组是值的语义列表(一个数组,其键从 0 开始,都是整数,并且之间没有间隙),则此函数返回 true。对于空数组,它也返回 true。请参阅以下代码片段以了解如何使用 array_is_list () 函数。 <?php /** * Returns true for empty array. */ array_is_list([]); /** * Returns true for sequential set of keys. */ array_is_list([1, 2, 3]); /** * Returns true as the first key is zero, and keys are in sequential order. * It is same as [0 => 'apple', 1 => 2, 2 => 3] */ array_is_list(['apple', 2, 3]); /** * Returns true as the first key is zero, and keys are in sequential order. * It is same as [0 => 'apple', 1 => 'scissor'] */ array_is_list(['apple', 'orange']); /** * Returns true as the first key is zero, and keys are in sequential order. * It is same as [0 => 'apple', 1 => 'scissor'] */ array_is_list([0 => 'apple', 'orange']); /** * Returns true as the first key is zero, and keys are in sequential order. */ array_is_list([0 => 'rock', 1 => 'scissor']); ?>键不是从 0 开始的数组,或者键不是整数,或者键是整数但不按顺序出现的数组将评估为 false。 <?php /** * Returns false as the first key does not start from zero. */ array_is_list([1 => 'apple', 'orange']); /** * Returns false as the first key does not start from zero. */ array_is_list([1 => 'apple', 0 => 'orange']); /** * Returns false as all keys are not integer. */ array_is_list([0 => 'apple', 'fruit' => 'orange']); /** * Returns false as the keys are not in sequential order. */ array_is_list([0 => 'apple', 2 => 'orange']); ?>7. 新的 fsync() 和 fdatasync() 函数 PHP 8.1 添加了对 fsync() 和 fdatasync() 函数的支持。两者都与现有 fflush() 函数有相似之处,该函数当前用于将缓冲区刷新到操作系统中。 然而,fsync() 和 fdatasync() 刷新该缓冲区到物理存储。它们之间的唯一区别是该 fsync() 函数在同步文件更改时包含元数据,而该 fdatasync() 函数不包含元数据。 fsync() 函数将采用文件指针并尝试将更改提交到磁盘。成功时返回 true,失败时返回 false,如果资源不是文件,则会发出警告。fdatasync() 函数的工作方式相同,但速度稍快一些,因为 fsync () 将尝试完全同步文件的数据更改和有关文件的元数据(上次修改时间等),这在技术上是两次磁盘写入。 请参阅以下代码片段以了解如何使用 fsync () 和 fdatasync () 函数。 <?php /** * Declare a variable and assign a filename. */ $fileName = 'notes.txt'; /** * Create the file with read and write permission. */ $file = fopen($fileName, 'w+'); /** * Add some text into the file. */ fwrite($file, 'Paragraph 1'); /** * Add a line break into the file. */ fwrite($file, "\r\n"); /** * Add some more text into the file. */ fwrite($file, 'Paragraph 2'); /** * You can use both the fsync() or fdatasync() functions * to commit changs to disk. */ fsync($file); // or fdatasync($file). /** * Close the open file pointer. */ fclose($file); ?>8. 对字符串键数组解包的支持 PHP 8.1 添加了对字符串键数组解包的支持。为了解压数组,PHP 使用展开 (…) 运算符。PHP 7.4 中引入了这个运算符来合并两个或多个数组,但语法更简洁。但在 PHP 8.1 之前,展开运算符仅支持带数字键的数组。请参阅以下代码片以了解如何将展开运算符用于字符串键控数组。 <?php /** * Declare an array */ $fruits1 = ['Jonathan Apples', 'Sapote']; /** * Declare another array */ $fruits2 = ['Pomelo', 'Jackfruit']; /** * Merge above two arrays using array unpacking. */ $unpackedFruits = [...$fruits1, ...$fruits2, ...['Red Delicious']]; /** * Print the above unpacked array. * This will print: * array(5) { * [0]=> * string(15) "Jonathan Apples" * [1]=> * string(6) "Sapote" * [2]=> * string(6) "Pomelo" * [3]=> * string(9) "Jackfruit" * [4]=> * string(13) "Red Delicious" * } */ var_dump($unpackedFruits); ?>9. $_FILES 新的用于目录上传的 full_path 键 PHP 8.1 添加了对 $_FILES 全局变量中 full_path 新键的支持。在 PHP 8.1 之前,$_FILES 没有存储到服务器的相对路径或确切目录。因此,您无法使用 HTML 文件上传表单上传整个目录。 新 full_path 键解决了这个问题。它存储相对路径并在服务器上重建确切的目录结构,使目录上传成为可能。请参阅以下代码片段以了解如何将 full_path 键与 $_FILES 全局变量一起使用。 <?php /** * Check if the user has submitted the form. */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { /** * Print the $_FILES global variable. This will display the following: * array(1) { * ["myfiles"]=> array(6) { * ["name"]=> array(2) { * [0]=> string(9) "image.png" * [1]=> string(9) "image.png" * } * ["full_path"]=> array(2) { * [0]=> string(25) "folder1/folder2/image.png" * [1]=> string(25) "folder3/folder4/image.png" * } * ["tmp_name"]=> array(2) { * [0]=> string(14) "/tmp/phpV1J3EM" * [1]=> string(14) "/tmp/phpzBmAkT" * } * // ... + error, type, size * } * } */ var_dump($_FILES); } ?> <form action="" method="POST" enctype="multipart/form-data"> <input name="myfiles[]" type="file" webkitdirectory multiple /> <button type="submit">Submit</button> </form>10. 新的 IntlDatePatternGenerator 类 PHP 8.1 添加了对新 IntlDatePatternGenerator 类的支持。在 PHP 8.1 之前,只能使用 IntlDateFormatter 。虽然它支持昨天、今天和明天使用的八种预定义格式,但是这些格式和 IntlDatePatternGenerator 不太一样。 这个类允许指定日期、月份和时间的格式,并且顺序将由类自动处理。请参阅以下代码片段以了解如何使用 IntlDatePatternGenerator 类。 <?php /** * Define a default date format. */ $skeleton = "YYYY-MM-dd"; /** * Parse a time string (for today) according to a specified format. */ $today = \DateTimeImmutable::createFromFormat('Y-m-d', date('Y-m-d')); /** * =========================== * PRINTING DATE IN USA FORMAT * =========================== * Initiate an instance for the IntlDatePatternGenerator class * and provide the locale information. * In the below example, I've used locale: en_US. */ $intlDatePatternGenerator = new \IntlDatePatternGenerator("en_US"); /** * Get the correct date format for the locale: en_US. * Following function "getBestPattern" will return: * MM/dd/YYYY */ $enUSDatePattern = $intlDatePatternGenerator->getBestPattern($skeleton); /** * Use the "formatObject" function of IntlDateFormatter to print as per specified pattern. * This will print the following: * Date in en-US: 12/03/2021 */ echo "Date in en-US: " . \IntlDateFormatter::formatObject($today, $enUSDatePattern, "en_US") . "\n"; /** * ============================= * PRINTING DATE IN INDIA FORMAT * ============================= * Initiate an instance for the IntlDatePatternGenerator class * and provide the locale information. * In the below example, I've used locale: en_IN. */ $intlDatePatternGenerator = new \IntlDatePatternGenerator("en_IN"); /** * Get the correct date format for the locale: en_IN. * Following function "getBestPattern" will return: * dd/MM/YYYY */ $enINDatePattern = $intlDatePatternGenerator->getBestPattern($skeleton); /** * Use the "formatObject" function of IntlDateFormatter to print as per specified pattern. * This will print the following: * Date in en-IN: 03/12/2021 */ echo "Date in en-IN: " . \IntlDateFormatter::formatObject($today, $enINDatePattern, "en_IN") . "\n"; ?>
技术教程
# PHP
易航
3年前
0
197
0
上一页
1
...
4
5
6
下一页