1 Star 2 Fork 1

myDcool / MengPHP

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
contribute
Sync branch
Cancel
Notice: Creating folder will generate an empty file .keep, because not support in Git
Loading...
README
MulanPSL-2.0

MengPHP

  • 模块化, 静态化, 层级少, 易调试, 支持多数据库链接/读写分离
  • 参考文档: http://doc.hearu.top/ (最近服务器被攻击, 可以到 /tool/document/ 目录下查看文档)
  • 如果不需要连接数据库或Redis可以不配置

一, 目录结构

MengPHP Framework
|-- core    框架的核心类
|-- config  配置文件
|-- libs    第三方库
|-- model   模型类, 理论上用于写获取数据的具体逻辑, 只放置在根目录下, 任何控制器都可以调用到
|-- tables  表结构信息, 自动从数据库读取表结构信息生成的类文件, 方便SQL组装和了解表结构
|-- router  路由规则文件
|-- modules 项目模块
|-- view   视图文件
|-- tool   框架自带的登录注册模块的SQL,数据库配置文件样例,windows启动php-cgi的脚本
|-- update   框架自更新脚本
|-- static  静态文件存放
|-- cli.php  命令行下的入口文件 php cli.php -q m_c_a
`-- index.php   入口文件

二, 安装步骤

1. 下载框架代码到

E:/php/code/project

2. 配置NGINX

# 精简版 (没有限速和安全配置)
http {
    ...
    
    server {
        listen       80;
        server_name  www.test.com;

        location ~ \.ico|jpg|gif|png|js|css$ {
            root E:/php/code/project/static;
            #expires 1h;
        }

        location / {
            root E:/php/code/project;
            # fastcgi_pass unix:/run/php-fpm/www.sock;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root/index.php;
            include        fastcgi_params;
        }
    
    }
}
# 增加限速和安全配置
http {
    ...
    # 限速全局配置, 详细用法可去nginx官网查询 (https://nginx.org/en/docs/ -> ngx_http_limit_req_module ngx_http_limit_conn_module)
    limit_rate 100k; # 每个链接限制 100k 字节
    limit_req_zone $binary_remote_addr zone=perip:5m rate=1r/s; # 单IP请求限制, 每秒1个, 5M的记录空间, 空间名为perip, 下边会用到
    limit_req_zone $server_name zone=perserver:5m rate=50r/s; # 单个server响应限制, 5M的记录空间, 空间名为perserver, 下边会用到
    ...
    server {
        listen       80;
        server_name  www.test.com;

        #限速配置 (也可以写在location中)
        limit_req zone=perip burst=5 nodelay; # 使用名为perip的限速设置, 超出的不再处理直接返回503
        limit_req zone=perserver burst=10; # 使用名为perserver的限速设置, 超出的排队等待处理

        #安全配置开始
        if ($request_method !~ ^(GET|POST)$) {return 405;}
        location ~ x0 {return 404;} # 8进制/16进制数据限制
        location ~ ^/\..*{return 404;} # 以.开始的访问限制(比如 .evn .git)
        location ~ \./.* {return 404;} # 路径访问限制 (比如: /../../abc.xxx)
        location ~* ^/http {return 404;}
        location ~* \.(php|asa|asp|aspx|html|git|sh|exe|xml|json)$ {return 404;} # 后缀限制
        #安全配置结束

        location ~ \.ico|jpg|gif|png|js|css$ {
            root E:/php/code/project/static;
            #expires 1h;
        }

        location / {
            root E:/php/code/project;
            # fastcgi_pass unix:/run/php-fpm/www.sock;
            fastcgi_pass   127.0.0.1:9720;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root/index.php;
            include        fastcgi_params;
        }
    
    }
}

3. 修改hosts文件,添加解析:127.0.0.1 www.test.com

4. 启动nginx;

5. 安装,启动php

  • windows:
    • 安装: 从官网下载最新的php代码, 解压到某个目录
    • 启动: 参考tool/script/ 目录下的启动脚本
  • Linux

6. 在浏览器中输入 www.test.com 访问首页

三, 核心功能使用说明

URL路由

核心代码参考 core/Route.php::matchURI();

1. 配置路由规则

  • 所有对外可访问的接口都要在 router/*.php 中配置映射规则, 接口与真正的方法是映射关系, 不直接暴露源代码的方法名
  • 路由规则分散在多个文件中, 防止多人协作开发时代码冲突

2. 配置举例

//router/test.php http://www.test.com/test/detail_123
$GLOBALS['router']['test'] = [
    'article_list_(\d+)' => 'article/home/get_list/page/$1',
    'detail_(\d{3})' => 'article/index/detail/id/$1',
];

//router/user.php http://www.test.com/user/login
$GLOBALS['router']['user'] = [
    //用户账号相关
    'default' => 'user/login', //都不匹配时走这个'default'路由
    'user' => 'user/index',
    'login' => 'user/login/index',
    'register' => 'user/register/index',
    'logout' => 'user/logout/index',
];

在命令行中使用路由

php cli.php -q cli/db_class  //指定去匹配router/cli.php中的路由

获取请求数据

参考 core/Request.php

1. 获取一个值

Request::Get('a', 'default');
Request::Post('a');
Request::Cookie('a');
Request::Route('a');
Request::Json('a'); //前端以json形式上传的数据(content-type: application/json)

2. 按类型获取

Request::Get()::Number('age', 11);
Request::Post()::Int('age', 11);
Request::Cookie()::Float('age', 1.11);
Request::Server()::String('name', 'zs');

3. 一次获取多个值, 没有则用默认值替代

Request::Post()::pickData(['a' => 0, 'b' => '', 'c' => '0']);

返回结果

参考 core/Response.php

1. 输出固定格式的json数据

$a = ['list' => [1,2,3,4]];

Response::json(10000, '用户列表', $a);

结果: {"code":10000,"msg":"\u7528\u6237\u5217\u8868","data":{"list":[1,2,3,4]}}

2. 便捷调用

Response::json()的简写, 返回结构是一样的

成功返回
Response::success($a);
Response::success($a, '用户列表');
Response::success($a, '用户列表', 20000);
失败返回
Response::error('参数错误');  // 结果: {"code":"-1","msg":"\u53c2\u6570\u9519\u8bef","data":[]]}

Response::error('参数错误', $a); // 结果: {"code":"-1","msg":"\u53c2\u6570\u9519\u8bef","data":{"list":[1,2,3,4]},"url":""}

Response::error('参数错误', $a, 20001); //结果: {"code":2001,"msg":"\u53c2\u6570\u9519\u8bef","data":{"list":[1,2,3,4]}}

3. 返回任意结构的json数据

Response::jsonReturn($a); //{"list":[1,2,3,4]}

4. 跳转

Response::notify('页面找不到啦~'); //页面找不到啦~

Response::redirect('充值成功, 页面即将跳转', 'http://www.hearu.top', 3);

Response::jump('http://www.hearu.top'); //直接跳转

返回HTML页面

参考: core/View.php

1. 显示单个页面

View::display();

2. 插入式显示页面(一个HTML页面框架, 里边有占位符:{{xxx}})

View::render();

数据库操作

更多增删改查操作请查看在线文档

use Tables\DefaultUser as User;

//增
$insertId = User::user()
    ->insert(['username' => '王五', 'age' => 18])
    ->insertId;

//删
$affectRows = User::user()
    ->where(['uid' => 5])
    ->delete()
    ->affectRows;

//改
$affectRows = User::user()
    ->where(['uid' => 1])
    ->updateVal(['age' => 20])
    ->updateOp('a', 'a', '+', 1)
    ->updateOp('a', 'b', '+', 2)
    ->update()
    ->affectRows;

//查
$rs = User::user()
    ->where(['status' => 0, 'deleted' => 0])
    ->whereOp('uid', '<', 10)
    ->order('uid desc')
    ->selectAll();

//join
$tbUser = User::$user;
$tbUserRole = User::$role_bind;
$tbRole = User::$role;

$rs = User::user()
    ->joinFields($tbUser, 'uid,username')
    ->joinFields($tbRole, 'name,access')
    ->joinTable([$tbUser, 'uid'],[$tbUserRole, 'uid'])
    ->joinTable([$tbUserRole, 'roleid'], [$tbRole, 'id'])
    ->where(['status' => 0, 'is_logout' => 0], $tbUser)
    ->where(['status' => 0], $tbUserRole)
    ->where(['status' => 0], $tbRole)
    ->joinAll();

Response::success($rs, DB::$currentSql);
    

文件日志

参考 libs/FileLog.php
日志文件存放的目录在入口文件 index.php 和 cli.php 中配置: LOGPATH

1. 常用

FileLog::info([msg], 'tag');  //日志文件: LOGPATH/info/yyyy-mm-dd.log, 数组内容会被转为json, 字符串会原样输出

FileLog::error('哈哈哈哈');

2. 设置日志跟踪ID

FileLog::$trace_id = time().Fun::randChar(5); //默认为 uniqid() 或 $_GET['trace_id'] 的值

Redis消息队列

  • 基础类在: libs/IRedis.php
  • 队列类在: model/RedisQueue.php
  • 队列名的配置在: config/topics.php
  • 具体实现参考: modules/cli/queue.php

DB消息队列

  • 队列类在: model/DBQueue.php
  • Topic的配置在: config/topics.php
  • 需要添加消费者的crontab (路由: cli_queue_db_consumer), 代码在 module/cli/queue_db.php

自带登录注册模块

  • 用户信息用cookie加密存储
  • 功能有: 登录/注册/退出, 其中注册提供图形验证码

自带前端单页面应用(SPA)样例

  • 按照上边说明安装好PHP运行环境
  • 配置好数据库信息(dbConfig.json)
  • 浏览器访问首页,即是一个可查看个多主机/数据库/表/字段等信息的web应用

四, 安全建议

代码级别

  • 尽量用post: 绝大部分的xss攻击是通过 <script> 等标签的 src 属性或href属性发起的"get"请求
  • 值中不能有\0截断符
  • 添加验证码: 防止外部构造表单请求, 要用在关键的地方(登录注册等), 不要影响到用户
  • 检测refer: 防止外部构造表单请求, 防止jsonp攻击, csrf攻击
  • 检测refer: 在返回头中构造白名单, header('Access-Control-Allow-Origin: http://www.a.com')
  • 一次性token: 用完就释放, 防止表单重复提交, 防止csrf攻击
  • include, file_get_content等使用时如果参数是URL,就得验证是否是白名单内的域名, 否则会包含/引入危险的文件
  • 对参数进行url_decode 防止 相对路径攻击(../../....)和javascript变相攻击
  • set cookie 的时候最好设置httponly, 这样就只能通过抓包来获取cookie注入脚本的方法就不行了
  • 获取cookie时限制跟ip相关, 这样通过xss的方法获取的cookie就不能被乱用了
  • html 标签可以指定本页面以后相对路径的根路径URL, 所以链接都要用全URL路径
  • 表单中过滤掉html注释符 "", 防止表单回填的时候被攻击
  • 表单中过滤掉select insert replace delete

服务器级别

  • 访问限速配置
  • 黑名单配置, 定期查看 access.log 找到异常访问, 在nginx中过滤
  • 防火墙只开放指定端口
  • iftop -P, nethogs, netstat 等命令查看异常访问进程或端口

其他

  • 上传的临时文件夹不要有可执行的权限,最好用第三方存储
木兰宽松许可证, 第2版 木兰宽松许可证, 第2版 2020年1月 http://license.coscl.org.cn/MulanPSL2 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第2版(“本许可证”)的如下条款的约束: 0. 定义 “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 “法人实体”是指提交贡献的机构及其“关联实体”。 “关联实体”是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 1. 授予版权许可 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 2. 授予专利许可 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 3. 无商标许可 “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 4. 分发限制 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 5. 免责声明与责任限制 “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 6. 语言 “本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。 条款结束 如何将木兰宽松许可证,第2版,应用到您的软件 如果您希望将木兰宽松许可证,第2版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; 3, 请将如下声明文本放入每个源文件的头部注释中。 Copyright (c) [Year] [name of copyright holder] [Software Name] is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. Mulan Permissive Software License,Version 2 Mulan Permissive Software License,Version 2 (Mulan PSL v2) January 2020 http://license.coscl.org.cn/MulanPSL2 Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions: 0. Definition Software means the program and related documents which are licensed under this License and comprise all Contribution(s). Contribution means the copyrightable work licensed by a particular Contributor under this License. Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. Legal Entity means the entity making a Contribution and all its Affiliates. Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. 1. Grant of Copyright License Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. 2. Grant of Patent License Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. 3. No Trademark License No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4. 4. Distribution Restriction You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. 5. Disclaimer of Warranty and Limitation of Liability THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 6. Language THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL. END OF THE TERMS AND CONDITIONS How to Apply the Mulan Permissive Software License,Version 2 (Mulan PSL v2) to Your Software To apply the Mulan PSL v2 to your work, for easy identification by recipients, you are suggested to complete following three steps: i Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner; ii Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package; iii Attach the statement to the appropriate annotated syntax at the beginning of each source file. Copyright (c) [Year] [name of copyright holder] [Software Name] is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details.

About

模块化小型PHP框架 expand collapse
PHP and 5 more languages
MulanPSL-2.0
Cancel

Releases

No release

Contributors

All

Activities

Load More
can not load any more
PHP
1
https://gitee.com/myDcool/meng-php.git
git@gitee.com:myDcool/meng-php.git
myDcool
meng-php
MengPHP
master

Search