Home Backend Development PHP Tutorial How to dynamically modify configuration files in PHP

How to dynamically modify configuration files in PHP

Jun 11, 2018 am 11:13 AM
Add, delete, modify and check Configuration file

This article mainly introduces how to dynamically modify the configuration file in PHP. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

A dynamic website generally has various Backend configuration, if the amount of configuration is not large, it would be a waste of resources to design a separate table

Some children like to store various configurations directly in the project. If you want to control the backend, you need a Here’s how to add, delete, modify, and check configuration files.

Let’s not talk nonsense, da~da~da~

Create a new PHP file and name it Config.class.php. Then just use it according to the content in the comments~

/* 
* @link https://mkblog.cn/ 
* @author mengkun 
* @license MIT 
*/  

/** 
 * PHP 无数据库配置文件增删查改模块 
 * !注:本模块未对高并发进行优化兼容,如果数据量或并发过大,还是用数据库比较好 ? 
 *  
 * 使用方法: 
 *  
 * 一、引用本模块 
 *  
 *  require_once 'Config.class.php'; 
 *  
 *  
 * 二、初始化 
 *  
 *  $C = new Config('配置文件名');  // * 如果是在二级目录下,请确保该目录存在 
 *  
 *  
 * 三、内置方法 
 *  
 *  - 存储(如果已存在则是修改)单条数据 
 *  
 *      $C->set('sitename', '哒哒哒'); 
 *  
 *  
 *  - 存储(如果已存在则是修改)一个数组 
 *       
 *      $C->set('user', array('name'=>'peter', 'age'=>12)); 
 *  
 *  
 *  - 读取一条数据 
 *  
 *      $C->get('user', '默认值'); 
 *  
 *  
 *  - 删除一条数据 
 *  
 *      $C->delete('user'); 
 *  
 *  
 *  - 保存对数据的修改 
 *  
 *      $C->save();     // 保存成功返回 true,否则返回失败原因 
 *  
 *   
 * * 注:为了避免频繁地写文件,以上所有对数据的操作都必须调用一次 $C->save(); 才会真正被保存到配置文件中 
 *       建议将所有的数据操作都执行完后再进行存储操作。 
 *  
 *  
 * * 附:精简写法 
 *  
 *      $C->set('sitename', '哒哒哒')->save(); 
 */  

define(&#39;CONFIG_EXIT&#39;, &#39;<?php exit;?>&#39;);  
class Config {  
    private $data;  
    private $file;  

    /** 
     * 构造函数 
     * @param $file 存储数据文件 
     * @return  
     */  
    function __construct($file) {  
        $file = $file.&#39;.php&#39;;  
        $this->file = $file;  
        $this->data= self::read($file);  
    }  

    /** 
     * 读取配置文件 
     * @param $file 要读取的数据文件 
     * @return 读取到的全部数据信息 
     */  
    public function read($file) {  
        if(!file_exists($file)) return array();  

        $str = file_get_contents($file);  
        $str = substr($str, strlen(CONFIG_EXIT));  
        $data = json_decode($str, true);  
        if (is_null($data)) return array();  
        return $data;  
    }  

    /** 
     * 获取指定项的值 
     * @param $key 要获取的项名 
     * @param $default 默认值 
     * @return data 
     */  
    public function get($key = null, $default = &#39;&#39;) {  
        if (is_null($key)) return $this->data;  // 取全部数据  

        if(isset($this->data[$key])) return $this->data[$key];  
        return $default;  
    }  

    /** 
     * 设置指定项的值 
     * @param $key 要设置的项名 
     * @param $value 值 
     * @return null 
     */  
    public function set($key, $value) {  
        if(is_string($key)) {   // 更新单条数据  
            $this->data[$key] = $value;  
        } else if(is_array($key)) {   // 更新多条数据                 
            foreach ($this->data as $k => $v) {  
                if ($v[$key[0]] == $key[1]) {  
                    $this->data[$k][$value[0]] = $value[1];  
                }  
            }  
        }  

        return $this;  
    }  

    /** 
     * 删除并清空指定项 
     * @param $key 删除项名 
     * @return null 
     */  
    public function delete($key) {  
        unset($this->data[$key]);  

        return $this;  
    }  

    /** 
     * 保存配置文件 
     * @param $file 要保存的数据文件 
     * @return true-成功 其它-保存失败原因 
     */  
    public function save() {  
        if(defined(&#39;JSON_PRETTY_PRINT&#39;)) {  
            $jsonStr = json_encode($this->data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);  
        } else {  
            $jsonStr = json_encode($this->data);  
        }  

        // 含有二进制或非utf8字符串对应检测  
        if(is_null($jsonStr)) return &#39;数据文件有误&#39;;  
        $buffer = CONFIG_EXIT.$jsonStr;  

        $file_strm = fopen($this->file, &#39;w&#39;);  
        if(!$file_strm) return &#39;写入文件失败,请赋予 &#39;.$file.&#39; 文件写权限!&#39;;  
        fwrite($file_strm, $buffer);  
        fclose($file_strm);  
        return true;  
    }  
}
Copy after login
Copy after login

Code interception source mengken blog

A dynamic website usually has various background configurations. If there is not much configuration, design a separate one The table seems to be a waste of resources

Some children like to store various configurations directly in the project. If they want to control the background, they need a set of operation methods to add, delete, modify and check the configuration files

Let’s not talk nonsense, da~da~da~

Create a new PHP file, name it Config.class.php, and then use it according to the content in the comments~

/* 
* @link https://mkblog.cn/ 
* @author mengkun 
* @license MIT 
*/  

/** 
 * PHP 无数据库配置文件增删查改模块 
 * !注:本模块未对高并发进行优化兼容,如果数据量或并发过大,还是用数据库比较好 ? 
 *  
 * 使用方法: 
 *  
 * 一、引用本模块 
 *  
 *  require_once &#39;Config.class.php&#39;; 
 *  
 *  
 * 二、初始化 
 *  
 *  $C = new Config(&#39;配置文件名&#39;);  // * 如果是在二级目录下,请确保该目录存在 
 *  
 *  
 * 三、内置方法 
 *  
 *  - 存储(如果已存在则是修改)单条数据 
 *  
 *      $C->set(&#39;sitename&#39;, &#39;哒哒哒&#39;); 
 *  
 *  
 *  - 存储(如果已存在则是修改)一个数组 
 *       
 *      $C->set(&#39;user&#39;, array(&#39;name&#39;=>&#39;peter&#39;, &#39;age&#39;=>12)); 
 *  
 *  
 *  - 读取一条数据 
 *  
 *      $C->get(&#39;user&#39;, &#39;默认值&#39;); 
 *  
 *  
 *  - 删除一条数据 
 *  
 *      $C->delete(&#39;user&#39;); 
 *  
 *  
 *  - 保存对数据的修改 
 *  
 *      $C->save();     // 保存成功返回 true,否则返回失败原因 
 *  
 *   
 * * 注:为了避免频繁地写文件,以上所有对数据的操作都必须调用一次 $C->save(); 才会真正被保存到配置文件中 
 *       建议将所有的数据操作都执行完后再进行存储操作。 
 *  
 *  
 * * 附:精简写法 
 *  
 *      $C->set(&#39;sitename&#39;, &#39;哒哒哒&#39;)->save(); 
 */  

define(&#39;CONFIG_EXIT&#39;, &#39;<?php exit;?>&#39;);  
class Config {  
    private $data;  
    private $file;  

    /** 
     * 构造函数 
     * @param $file 存储数据文件 
     * @return  
     */  
    function __construct($file) {  
        $file = $file.&#39;.php&#39;;  
        $this->file = $file;  
        $this->data= self::read($file);  
    }  

    /** 
     * 读取配置文件 
     * @param $file 要读取的数据文件 
     * @return 读取到的全部数据信息 
     */  
    public function read($file) {  
        if(!file_exists($file)) return array();  

        $str = file_get_contents($file);  
        $str = substr($str, strlen(CONFIG_EXIT));  
        $data = json_decode($str, true);  
        if (is_null($data)) return array();  
        return $data;  
    }  

    /** 
     * 获取指定项的值 
     * @param $key 要获取的项名 
     * @param $default 默认值 
     * @return data 
     */  
    public function get($key = null, $default = &#39;&#39;) {  
        if (is_null($key)) return $this->data;  // 取全部数据  

        if(isset($this->data[$key])) return $this->data[$key];  
        return $default;  
    }  

    /** 
     * 设置指定项的值 
     * @param $key 要设置的项名 
     * @param $value 值 
     * @return null 
     */  
    public function set($key, $value) {  
        if(is_string($key)) {   // 更新单条数据  
            $this->data[$key] = $value;  
        } else if(is_array($key)) {   // 更新多条数据                 
            foreach ($this->data as $k => $v) {  
                if ($v[$key[0]] == $key[1]) {  
                    $this->data[$k][$value[0]] = $value[1];  
                }  
            }  
        }  

        return $this;  
    }  

    /** 
     * 删除并清空指定项 
     * @param $key 删除项名 
     * @return null 
     */  
    public function delete($key) {  
        unset($this->data[$key]);  

        return $this;  
    }  

    /** 
     * 保存配置文件 
     * @param $file 要保存的数据文件 
     * @return true-成功 其它-保存失败原因 
     */  
    public function save() {  
        if(defined(&#39;JSON_PRETTY_PRINT&#39;)) {  
            $jsonStr = json_encode($this->data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);  
        } else {  
            $jsonStr = json_encode($this->data);  
        }  

        // 含有二进制或非utf8字符串对应检测  
        if(is_null($jsonStr)) return &#39;数据文件有误&#39;;  
        $buffer = CONFIG_EXIT.$jsonStr;  

        $file_strm = fopen($this->file, &#39;w&#39;);  
        if(!$file_strm) return &#39;写入文件失败,请赋予 &#39;.$file.&#39; 文件写权限!&#39;;  
        fwrite($file_strm, $buffer);  
        fclose($file_strm);  
        return true;  
    }  
}
Copy after login
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

thinkphp common path usage analysis

PHPMailer ThinkPHP realizes the automatic sending email function

The above is the detailed content of How to dynamically modify configuration files in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
How to enable or disable eSIM on Windows 11 How to enable or disable eSIM on Windows 11 Sep 20, 2023 pm 05:17 PM

If you bought your laptop from a mobile operator, you most likely had the option to activate an eSIM and use your cellular network to connect your computer to the Internet. With eSIM, you don't need to insert another physical SIM card into your laptop because it's already built-in. It is very useful when your device cannot connect to the network. How to check if my Windows 11 device is eSIM compatible? Click the Start button and go to Network & Internet &gt; Cellular &gt; Settings. If you don't see the "Cellular" option, your device doesn't have eSIM capabilities and you should check another option, such as using your mobile device to connect your laptop to a hotspot. In order to activate and

Super complete! Common ways to write configuration files in Python Super complete! Common ways to write configuration files in Python Apr 11, 2023 pm 10:22 PM

Why should we write the fixed file of the configuration file? We can directly write it as a .py file, such as settings.py or config.py. The advantage of this is that we can directly import parts of it through import in the same project; but if we need to use it in other When sharing configuration files on non-Python platforms, writing a single .py is not a good choice. At this time we should choose a common configuration file type to store these fixed parts. Currently, the commonly used and popular configuration file format types mainly include ini, json, toml, yaml, xml, etc. We can access these types of configuration files through standard libraries or third-party libraries.

How to change network type to private or public in Windows 11 How to change network type to private or public in Windows 11 Aug 24, 2023 pm 12:37 PM

Setting up a wireless network is common, but choosing or changing the network type can be confusing, especially if you don't know the consequences. If you're looking for advice on how to change the network type from public to private or vice versa in Windows 11, read on for some helpful information. What are the different network profiles in Windows 11? Windows 11 comes with a number of network profiles, which are essentially sets of settings that can be used to configure various network connections. This is useful if you have multiple connections at home or office so you don't have to set it all up every time you connect to a new network. Private and public network profiles are two common types in Windows 11, but generally

Where is the win10 user profile? How to set the user profile in Win10 Where is the win10 user profile? How to set the user profile in Win10 Jun 25, 2024 pm 05:55 PM

Recently, many Win10 system users want to change the user profile, but they don’t know how to do it. This article will show you how to set the user profile in Win10 system! How to set up user profile in Win10 1. First, press the "Win+I" keys to open the settings interface, and click to enter the "System" settings. 2. Then, in the opened interface, click "About" on the left, then find and click "Advanced System Settings". 3. Then, in the pop-up window, switch to the "" option bar and click "User Configuration" below.

How does Go language implement the addition, deletion, modification and query operations of the database? How does Go language implement the addition, deletion, modification and query operations of the database? Mar 27, 2024 pm 09:39 PM

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

Super complete! Common ways to write configuration files in Python Super complete! Common ways to write configuration files in Python Apr 13, 2023 am 08:31 AM

Why write configuration files? During the development process, we often use some fixed parameters or constants. For these more fixed and commonly used parts, they are often written into a fixed file to avoid repetition in different module codes and keep the core code clean. We can directly write this fixed file into a .py file, such as settings.py or config.py. The advantage of this is that we can directly import parts of it through import in the same project; but if we need to do it on other non-Python platforms When configuring file sharing, writing a single .py is not a good choice. At this time we should choose a common configuration file type

Effective method to solve the problem of garbled characters in the eclipse editor Effective method to solve the problem of garbled characters in the eclipse editor Jan 04, 2024 pm 06:56 PM

An effective method to solve the garbled problem of eclipse requires specific code examples. In recent years, with the rapid development of software development, eclipse, as one of the most popular integrated development environments, has provided convenience and efficiency to many developers. However, you may encounter garbled code problems when using eclipse, which brings trouble to project development and code reading. This article will introduce some effective methods to solve the problem of garbled characters in Eclipse and provide specific code examples. Modify eclipse file encoding settings: in eclip

Install Helm on Ubuntu Install Helm on Ubuntu Mar 20, 2024 pm 06:41 PM

Helm is an important component of Kubernetes that simplifies the deployment of Kubernetes applications by bundling configuration files into a package called HelmChart. This approach makes updating a single configuration file more convenient than modifying multiple files. With Helm, users can easily deploy Kubernetes applications, simplifying the entire deployment process and improving efficiency. In this guide, I'll cover different ways to implement Helm on Ubuntu. Please note: The commands in the following guide apply to Ubuntu 22.04 as well as all Ubuntu versions and Debian-based distributions. These commands are tested and should work correctly on your system. in U

See all articles