Can one .PHP file edit another?
So I have a file for constants. I want to let user define them and then edit my .php filr with that global constants (not xml - real PHP file )
With such code for example
<?php
// Database Constants
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "000000");
define("DB_NAME", "cms");
?>
How to edit this .php file from another PHP file? Is it possible?
Btw开发者_运维知识库 in future I want to implement not only constants redefining but some smart code that will be able to modify itself.
If someone can, please show me a function to change word "localhost" in my file...
Your can write program that edit any file including php file.
BTW. Be carefull! If you show your program how to modify itself it may do it over and over very fast, and finally start killing people like in matrix or terminator movies...
FILE_TO_REPLACE_IN.php:
<?php
define("DB_SERVER", "{DB_SERVER}");
define("DB_USER", "{DB_USER}");
define("DB_PASS", "{DB_PASS}");
define("DB_NAME", "{DB_NAME}");
SCRIPT_TO_CHANGE_WITH.php:
<?php
$searchF = array('{DB_SERVER}','{DB_USER}','{DB_PASS}','{DB_NAME}');
$replaceW = array('localhost', 'user', 'pass', 'db');
$fh = fopen("FILE_TO_REPLACE_IN.php", 'w');
$file = file_get_contents($fh);
$file = str_replace($searchF, $replaceW, $file);
fwrite($fh, $file);
... or something like that.
Take a look at Zend's CodeGenerator module. Using the reflection api you can create files and classes programatically.
if you are designing your own solution you should refrain from using metaprogramming (check wikipedia) for configuration purposes.
php has a built-in ini-file parser you can use. when you've only got key-value pairs that is sufficient.
writing:
<?php
file_put_contents("settings.ini","[auth]
DB_SERVER=".DB_SERVER."
DB_USER=".DB_USER."
DB_PASS=".DB_PASS."
DB_NAME=".DB_NAME."
");
?>
reading:
<?php
$auth = parse_ini_file("settings.ini");
foreach ($auth as $k => $v) {
define($k,$v);
}
?>
Not talking about security, one simple way is that you can read the php file using reading functions like file_get_contents
and once you have the contents, you should show them in some textarea
where your users could edit it. Once they edit it and submit the form, you should update the info.
it is possible... But you will need basic PHP skills.
Use fopen
or file_put_contents
. Easiest way is to write whole PHP file from scratch...
Using fopen()
fwrite()
and consorts you can edit any kind of file, including php ones.
You can open the file
$lines = file('myConstants.php');
Edit the content and than save it back
$myFile = 'myConstants.php'
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, 'DATA HERE');
fclose($fh);
精彩评论