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);
}
}
難道不是說'$ new_content'仍然是空的嗎?因此用什麼都替換你的文件... – JustBaron
不可能。因爲它不是空的,所以至少寫一些。 – YumYumYum
我試過安全寫。但還是一樣。它清除文件數據並保留1個部分。 – YumYumYum