2017-09-07 37 views
1

我有现有的ini文件,它仅适用于Javascript操作的编辑。PHP - 不安全的文件编辑,删除所有数据

但是,PHP/Javascript清除ini文件中的所有数据,并在一行中留下一个部分。 (有时它没有消除,但是当section4或section5它的编辑它删除整个文件,并保留最后一个)

config.ini文件:

[slide1] 
button0=6,298,273,425 
[slide2] 
button1=1005,313,1269,425 
button0=6,298,273,425 
[slide3] 
button1=1005,313,1269,425 
button0=6,298,273,425 
[slide4] 
button1=1005,313,1269,425 
button0=6,298,273,425 
[slide5] 
button1=1005,313,1269,425 
button0=6,298,273,425 
button2=1005,313,1269,425 
button3=6,298,273,425 
[slide6] 

[slide7] 

PHP:

// EDIT only? (no erase, no delete, no new line add 
function config_set($config_file, $section, $key, $value) { 
    $config_data = parse_ini_file($config_file, true); 
    $config_data[$section][$key] = $value; 
    $new_content = ''; 
    foreach ($config_data as $section => $section_content) { 
     $section_content = array_map(function($value, $key) { 
      return "$key=$value"; 
     }, array_values($section_content), array_keys($section_content)); 
     $section_content = implode("\n", $section_content); 
     $new_content .= "[$section]\n$section_content\n"; 
    } 
    file_put_contents($config_file, $new_content); 
} 



config_set('config.ini', 'slide5', "button0", "1,2,3,4,5,5,6,7,7"); 
echo 'updated'; 

的jQuery:

$.get('draw_save.php', { 
     test: 'none' 
     }, function(msg) { 
     console.log(msg); 
     }); 

编辑:尝试安全写入

function safefilerewrite($fileName, $dataToSave) {  
    if ($fp = fopen($fileName, 'w')) { 
    $startTime = microtime(TRUE); 
    do {    
     $canWrite = flock($fp, LOCK_EX); 
     // If lock not obtained sleep 
     // for 0 - 100 milliseconds, to avoid collision and CPU load 
     if(!$canWrite) usleep(round(rand(0, 100)*1000)); 
    } while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5)); 

     //file was locked so now we can store information 
     if ($canWrite) {    
     fwrite($fp, $dataToSave); 
     flock($fp, LOCK_UN); 
     } 
     fclose($fp); 
    } 
} 
+0

难道不是说'$ new_content'仍然是空的吗?因此用什么都替换你的文件... – JustBaron

+0

不可能。因为它不是空的,所以至少写一些。 – YumYumYum

+0

我试过安全写。但还是一样。它清除文件数据并保留1个部分。 – YumYumYum

回答

0

延迟写入尝试修复它。

function save_later() { 
    // Ajax 
    $.get('draw_save.php', { 

    }, function(msg) { 
     console.log(msg); 
    });  
    } 



    var delay_saving = null; 
    function delay_save() { 
    delay_saving = setTimeout(function() { 
     save_later(); 
    }, 200); 
    } 
相关问题