学无先后,达者为师

网站首页 PHP其他 正文

php文件配置数组数据修改替换

作者:渡目成书 更新时间: 2022-01-28 PHP其他
  • 系统配置数据在php文件中需要能够动态配置
  • 一般情况下在开发系统的时候会把固定数据配置成文件进行统一调用,如第三方接口的秘钥,配置成文件,调用进行统一调用,在修改配置时候全局都能生效。但是这种修改一般是人手动在文件里面修改。作为一个系统,我们可以做得更为方便,可以在web页面进行文件的修改。
  • 这里以百度文字识别配置在laravel系统中为例子
  • 在laravel中一般都会把配置写进config文件下配置文件中,然后用config()函数进行调用
  • 例如这里baidu_ocr.php,配置了文件,我们希望在web端上能够进行修改
<?php
return [
    'appid'=>'xxxxxx',
    'apiKey'=>'xxxxxx',
    'secretKey'=>'xxxxxx'
];
  • 先对配置文件进行数据读取,获取到配置信息
$baidu_ocr = file_get_contents(base_path() . '/config/baidu_ocr.php');
        preg_match_all("/=>'(.*)'/", $baidu_ocr, $ocrs);
        $arr = $ocrs[1];

在这里插入图片描述

  • 我们获取到配置数据就可以渲染到页面上了
    在这里插入图片描述
  • 提交,修改配置文件,文件已经修改
$baidu_ocr = file_get_contents(base_path() . '/config/baidu_ocr.php');
        $baidu_ocr = preg_replace("/'appid'=>'(.*)'/", "'appid'=>'" . $request->appid . "'", $baidu_ocr);
        $baidu_ocr = preg_replace("/'apiKey'=>'(.*)'/", "'apiKey'=>'" . $request->apikey . "'", $baidu_ocr);
        $baidu_ocr = preg_replace("/'secretKey'=>'(.*)'/", "'secretKey'=>'" . $request->secretkey . "'", $baidu_ocr);
        file_put_contents(base_path() . '/config/baidu_ocr.php', $baidu_ocr);

在这里插入图片描述

<?php
return [
    'appid'=>'123456',
    'apiKey'=>'123456',
    'secretKey'=>'123456'
];

这种功能我们能在许多需要配置的开源系统非常常见,也可以使用数据库存储的方式更容易实现,但是配置文件的方式更好。

原文链接:https://blog.csdn.net/weixin_43674113/article/details/109236926

栏目分类
最近更新