dtcyv3985 2012-05-01 21:15
浏览 98
已采纳

将变量动态更新到现有文件中?

I'm trying to build a small CMS using CodeIgniter, and I need to be able to dynamically update some variables within the application/config.php

So far I did:

private function update_file ($file, $var, $var_name) {
    $start_tag = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
";
    if (file_exists($file)) {
        require_once ($file);
        $updated_array = array_merge($$var_name, $var);         
        $data = $start_tag."\$".$var_name." = ".var_export($updated_array, true).";";
        file_put_contents($file, $data);
    } else {
        return false;
    }
}

Everything works just fine! The result in the config.php file will be:

<?php ...;
$config = array (
'base_url' => '',
...
...
);

But what if I would like to maintain the original config.php file format with comments, spaces and
separated declared $config['key'] = 'value' ... ?

Is that possible ?


EDIT:

Thank you for your answers, very precious. I found a slightly different solution for my needs, performing a preg_replace on the return of file_get_contents() and then write back on the file the new resulting string. File maintains the exact original clean format.

private function update_file ($file, $var, $var_name) {
    if (file_exists($file)) {
        require_once ($file);

        $contents = file_get_contents($file);
        $updated_array = array_merge($$var_name, $var);
        $search = array();
        $replace = array();

        foreach($$var_name as $key => $val) {
            $pattern = '/\$'.$var_name.'\[\\\''.$key.'\\\'\]\s+=\s+[^\;]+/';
            $replace_string = "\$".$var_name."['".$key."'] = ".var_export($updated_array[$key], true);      
            array_push($search, $pattern);
            array_push($replace, $replace_string);
        }

        $new_contents = preg_replace($search, $replace, $contents);
        write_file($file, $new_contents);
}

Maybe it requires some slight performance improvements. But this is my baseline idea.

  • 写回答

2条回答 默认 最新

  • dsfs504545 2012-05-01 21:31
    关注

    It is possible. I can't find the code , but once i have written something like that. Whole idea was based on tokenizing template file and substitute values in an array, preserving key order, line numbers and comments from the template.

    [+] Found it. It's purpose was to fill values from template that looked like this (it was much bigger of course):

    <?php
    
    $_CFG = array(
    
        // DB section
        'db_host' => 'localhost',
        'db_user' => 'root',
        'db_pass' => '',
        'db_name' => 'test',
    
        // Site specific
        'lang' => array('pl','en'),
        'admin' => 'admin@example.com',
    );
    

    And the code that was doing all the magic:

    $tokens = token_get_all(file_get_contents('tpl/config.php'));
    
    $level = -1;
    $buffer = '';
    $last_key = 0;
    $iteration = 0;
    
    foreach($tokens as $t){
        if($t === ')'){
            $iteration = 0;
            $last_key = 0;
            $level--;
        }
    
        if(is_array($t)){
            if($t[0] == T_ARRAY && strtolower($t[1]) === 'array')
                $level++;
    
            if($t[0] == T_CONSTANT_ENCAPSED_STRING){
                if($last_key){
                    if($level){
                        if(isset($new_config[$last_key][$iteration])){
                            $buffer .= var_export($new_config[$last_key][$iteration], TRUE);
                        }
                        else
                            $buffer .= 'null';
    
                        $iteration++;
                    }
                    else{
                        if(isset($new_config[$last_key]))
                            $buffer .= var_export($new_config[$last_key], TRUE);
                        else
                            $buffer .= 'null';
    
                        $last_key = 0;
                    }
                }
                else{
                    $buffer .= $t[1];
                    $last_key = trim($t[1],"'");
                }
            }
            else
                $buffer .= $t[1];
        }
        else
            $buffer .= $t;
    }
    
    file_put_contents('config.php',$buffer);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 idea自动补全键位冲突
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页