Can I edit a .PHP file?

So, I have a file for constants. I want the user to define them and then edit my .php filr with these global constants (and not xml - the 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?

In the future, I want to implement not only constant overrides, but also some intelligent code that can modify itself.

If someone can, please show me the function to change the word "localhost" in my file ...

+3
source share
8 answers

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.

+5
source

, , php .

BTW. ! , , , , , ...

+6
+2

, ( ) .

php ini-file parser, . -.

:

<?php
file_put_contents("settings.ini","[auth]
DB_SERVER=".DB_SERVER."
DB_USER=".DB_USER."
DB_PASS=".DB_PASS."
DB_NAME=".DB_NAME."
");
?>

:

<?php
$auth = parse_ini_file("settings.ini");
foreach ($auth as $k => $v) {
define($k,$v);
}
?>
+2

, - php, , file_get_contents, , , textarea, . , .

0

... PHP.

fopen file_put_contents. - PHP ...

0

fopen() fwrite() , php.

0

$lines = file('myConstants.php');

$myFile = 'myConstants.php'
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, 'DATA HERE');
fclose($fh);
0

Source: https://habr.com/ru/post/1739853/


All Articles