search
HomeBackend DevelopmentPHP TutorialHow 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 checkConfiguration 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;  
    }  
}

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;  
    }  
}

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
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)