How to dynamically modify configuration files in PHP
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('CONFIG_EXIT', '<?php exit;?>'); class Config { private $data; private $file; /** * 构造函数 * @param $file 存储数据文件 * @return */ function __construct($file) { $file = $file.'.php'; $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 = '') { 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('JSON_PRETTY_PRINT')) { $jsonStr = json_encode($this->data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT); } else { $jsonStr = json_encode($this->data); } // 含有二进制或非utf8字符串对应检测 if(is_null($jsonStr)) return '数据文件有误'; $buffer = CONFIG_EXIT.$jsonStr; $file_strm = fopen($this->file, 'w'); if(!$file_strm) return '写入文件失败,请赋予 '.$file.' 文件写权限!'; 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 '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('CONFIG_EXIT', '<?php exit;?>'); class Config { private $data; private $file; /** * 构造函数 * @param $file 存储数据文件 * @return */ function __construct($file) { $file = $file.'.php'; $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 = '') { 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('JSON_PRETTY_PRINT')) { $jsonStr = json_encode($this->data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT); } else { $jsonStr = json_encode($this->data); } // 含有二进制或非utf8字符串对应检测 if(is_null($jsonStr)) return '数据文件有误'; $buffer = CONFIG_EXIT.$jsonStr; $file_strm = fopen($this->file, 'w'); if(!$file_strm) return '写入文件失败,请赋予 '.$file.' 文件写权限!'; 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!

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

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

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

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.

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

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.

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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
Visual web development tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
