我们做开发的时,很多地方都需要调用一些公共的配置信息,如网站名称、客服电话等基础信息,我们先来介绍一下通过后台修改配置文件的方法。
逻辑:
模板文件设置好表单
根据表单提交的数据拼接成配置文件的数组格式,然后将拼接成的字符串通过file_put_contents函数写入配置文件即可。
控制器文件System.php
/** * 修改配置文件 */ public function index(){ if(request()->isAjax()){ $filename = Env::get('config_path').'config_base.php'; file_put_contents($filename, "<?php\nreturn " . var_export($_POST['data'], true) . ";"); return json(['code' => 1, 'data' => '', 'msg' => '保存成功!']); } return $this->fetch(); }
前提是先添加一个配置文件,我这里的配置文件地址是/config/config_base.php
模板表单
<form class="layui-form " action=""> <div class="layui-form-item"> <label class="layui-form-label"> <span class='x-red'>*</span>系统名称 </label> <div class="layui-input-inline"> <input type="text" name="site_name" value="{$Think.config.config_base.site_name}" autocomplete="off" placeholder="控制在25个字、50个字节以内" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"> 昵称 </label> <div class="layui-input-inline"> <input type="text" name="nickname" value="{$Think.config.config_base.nickname}" autocomplete="off" placeholder="" class="layui-input" style="width: 240px;"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"> 籍贯 </label> <div class="layui-input-inline"> <input type="text" name="native_place" value="{$Think.config.config_base.native_place}" autocomplete="off" placeholder="" class="layui-input" style="width: 240px;"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">微信</label> <div class="layui-input-inline"> <input type="text" name="wechat" value="{$Think.config.config_base.wechat}" autocomplete="off" placeholder="" class="layui-input" style="width: 240px;"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">QQ</label> <div class="layui-input-inline"> <input type="text" name="qq" value="{$Think.config.config_base.qq}" autocomplete="off" placeholder="" class="layui-input" style="width: 240px;"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">Email</label> <div class="layui-input-inline"> <input type="text" name="email" value="{$Think.config.config_base.email}" autocomplete="off" placeholder="" class="layui-input" style="width: 240px;"> </div> </div> <div class="layui-form-item"> <button class="layui-btn" lay-submit="" lay-filter="setting_base"> 保存 </button> </div> </form>
js
<script> layui.use(['element','layer','form','upload'], function(){ $ = layui.jquery;//jquery lement = layui.element;//面包导航 layer = layui.layer;//弹出层 upload = layui.upload; form = layui.form //监听提交 form.on('submit(setting_base)', function(data){ //发异步,把数据提交给php $.post("{:url('index')}", {'data' : data.field}, function(res){ if(res.code == 1){ layer.alert(res.msg, {icon: 6}); }else{ layer.msg(res.msg,{icon:0,time:1500,shade: 0.1}); } }); return false; }); }) </script>